From 78e3a42c4b4859e104eaafeb5fce0949ab728237 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 1 Dec 2024 13:40:13 +0100 Subject: [PATCH] day(01): solve first day Signed-off-by: Matej Focko --- inputs/day01/sample.txt | 6 +++++ src/Day01.kt | 51 ++++++++++++++++++++++++++++++----------- 2 files changed, 43 insertions(+), 14 deletions(-) create mode 100644 inputs/day01/sample.txt diff --git a/inputs/day01/sample.txt b/inputs/day01/sample.txt new file mode 100644 index 0000000..dfca0b1 --- /dev/null +++ b/inputs/day01/sample.txt @@ -0,0 +1,6 @@ +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 \ No newline at end of file diff --git a/src/Day01.kt b/src/Day01.kt index d1bb47c..dd8845a 100644 --- a/src/Day01.kt +++ b/src/Day01.kt @@ -1,21 +1,44 @@ +fun parseInput(inputType: String): Pair, MutableList> = + readInput(1, inputType).fold(mutableListOf() to mutableListOf()) { (left, right), line -> + val nums = line.split(Regex("\\s+")) + + left.add(nums[0].toInt()) + right.add(nums[1].toInt()) + + left to right + } + +fun precompute(input: Pair, MutableList>) { + input.first.sort() + input.second.sort() +} + +fun part1(input: Pair, List>): Int = + input.first.zip(input.second).sumOf { (l, r) -> maxOf(l - r, r - l) } + +fun part2(input: Pair, List>): Int { + val (left, right) = input + val freqs = buildMap { + right.forEach { it -> + put(it, 1 + getOrDefault(it, 0)) + } + } + + return left.sumOf { it -> it * freqs.getOrDefault(it, 0) } +} + fun main() { - fun part1(input: List): Int { - return input.size - } + // Test of sample + val testInput = parseInput("sample") + precompute(testInput) - fun part2(input: List): Int { - return input.size - } + check(part1(testInput) == 11) + check(part2(testInput) == 31) - // Test if implementation meets criteria from the description, like: - check(part1(listOf("test_input")) == 1) + // Challenge input + val input = parseInput("input") + precompute(input) - // 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") part1(input).println() part2(input).println() }