From a92bf3b96ffdc4c4099db4ba80e84d3fc74e6c24 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 7 Dec 2021 10:50:38 +0100 Subject: [PATCH] day(07): add solution Signed-off-by: Matej Focko --- src/day07/Day07.kt | 29 +++++++++++++++++++++++++++++ src/day07/test_input.txt | 1 + 2 files changed, 30 insertions(+) create mode 100644 src/day07/Day07.kt create mode 100644 src/day07/test_input.txt diff --git a/src/day07/Day07.kt b/src/day07/Day07.kt new file mode 100644 index 0000000..6215c40 --- /dev/null +++ b/src/day07/Day07.kt @@ -0,0 +1,29 @@ +package day07 + +import readInputAsCommaSeparatedInts +import kotlin.math.absoluteValue + +// for part 1, it's always included in the input set +fun part1(input: List): Int = input.toSet().minOf { target -> + input.sumOf { + (it - target).absoluteValue + } +} + +fun part2(input: List): Int = (input.minOrNull()!!..input.maxOrNull()!!).minOf { target -> + input.sumOf { + val diff = (it - target).absoluteValue + diff * (diff + 1) / 2 + } +} + +fun main() { + val testInput = readInputAsCommaSeparatedInts(7, "test_input").sorted() + val input = readInputAsCommaSeparatedInts(7, "input").sorted() + + check(part1(testInput) == 37) + println(part1(input)) + + check(part2(testInput) == 168) + println(part2(input)) +} diff --git a/src/day07/test_input.txt b/src/day07/test_input.txt new file mode 100644 index 0000000..2bdd92f --- /dev/null +++ b/src/day07/test_input.txt @@ -0,0 +1 @@ +16,1,2,0,4,2,7,1,2,14 \ No newline at end of file