From 88f9e0b58f36ca796467718457bb570348f67d18 Mon Sep 17 00:00:00 2001 From: hduprat Date: Sun, 1 Dec 2024 16:09:26 +0100 Subject: [PATCH] Day 1 --- src/Day01.kt | 42 ++++++++++++++++++++++++++++++++++-------- src/_template.kt | 18 ++++++++++++++++++ 2 files changed, 52 insertions(+), 8 deletions(-) create mode 100644 src/_template.kt diff --git a/src/Day01.kt b/src/Day01.kt index d1bb47c..86040ff 100644 --- a/src/Day01.kt +++ b/src/Day01.kt @@ -1,21 +1,47 @@ +import kotlin.math.abs + +data class LocationLists(val left: List, val right: List) + fun main() { + fun getLocationLists(input: List): LocationLists { + val leftList = mutableListOf() + val rightList = mutableListOf() + + input.forEach { + val splits = it.split(Regex("\\s+"),2) + leftList.add(splits[0].toInt()) + rightList.add(splits[1].toInt()) + } + + return LocationLists(leftList.sorted(), rightList.sorted()) + } + fun part1(input: List): Int { - return input.size + + val locationLists = getLocationLists(input) + + return locationLists.left.foldIndexed(0) {index, acc, elt -> + val distance = abs(elt-locationLists.right[index]) + distance + acc + } } fun part2(input: List): Int { - return input.size - } + val locationLists = getLocationLists(input) - // Test if implementation meets criteria from the description, like: - check(part1(listOf("test_input")) == 1) + return locationLists.left.fold(0) { acc, elt -> + val similarityScore = elt * locationLists.right.count { it == elt } + similarityScore + acc + } + } // Or read a large test input from the `src/Day01_test.txt` file: val testInput = readInput("Day01_test") - check(part1(testInput) == 1) - - // Read the input from the `src/Day01.txt` file. val input = readInput("Day01") + + check(part1(testInput) == 11) part1(input).println() + + check(part2(testInput) == 31) part2(input).println() } diff --git a/src/_template.kt b/src/_template.kt new file mode 100644 index 0000000..e784460 --- /dev/null +++ b/src/_template.kt @@ -0,0 +1,18 @@ +fun main() { + fun part1(input: List): Int { + return input.size + } + + fun part2(input: List): Int { + return input.size + } + + val testInput = readInput("DayXX_test") + val input = readInput("DayXX") + + check(part1(testInput) == 1) + part1(input).println() + + check(part2(testInput) == 1) + part2(input).println() +}