From f49cf34ce0ccd9efdb550bf210b155cab32b981d Mon Sep 17 00:00:00 2001 From: William Brawner Date: Fri, 8 Dec 2023 22:44:53 -0700 Subject: [PATCH] Add solution to day 9 --- src/Day09.kt | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/Day09.kt diff --git a/src/Day09.kt b/src/Day09.kt new file mode 100644 index 0000000..4b60a5d --- /dev/null +++ b/src/Day09.kt @@ -0,0 +1,64 @@ +fun main() { + fun part1(input: List): Int { + return input.toHistories() + .sequences() + .extrapolate() + .sumOf { it.last().last() } + .also { it.println() } + } + + fun part2(input: List): Int { + return input.toHistories() + .sequences() + .extrapolatePrevious() + .sumOf { it.last().first() } + .also { it.println() } + } + + // test if implementation meets criteria from the description, like: + val testInput = readInput("Day09_test") + check(part1(testInput) == 114) + + val input = readInput("Day09") + part1(input).println() + check(part2(testInput) == 2) + part2(input).println() +} + +fun List.toHistories(): List> = map { line -> line.split(' ').map { it.toInt() } } + +fun List>.sequences() = map { history -> + val differences = mutableListOf(history.toMutableList()) + var nextSequence = history.toMutableList() + while (nextSequence.any { it != 0 }) { + nextSequence = nextSequence.zipWithNext { a, b -> b - a }.toMutableList() + differences.add(nextSequence) + } + differences +} + +fun List>>.extrapolate() = map { history -> + val bottomUpHistory = history.asReversed() + bottomUpHistory.mapIndexed { index, sequence -> + if (index == 0) { + sequence.add(0) + } else { + val other = bottomUpHistory[index - 1].last() + sequence.add(sequence.last() + other) + } + sequence + } +} + +fun List>>.extrapolatePrevious() = map { history -> + val bottomUpHistory = history.asReversed() + bottomUpHistory.mapIndexed { index, sequence -> + if (index == 0) { + sequence.add(0, 0) + } else { + val other = bottomUpHistory[index - 1].first() + sequence.add(0, sequence.first() - other) + } + sequence + } +} \ No newline at end of file