diff --git a/src/main/kotlin/no/rodland/advent_2023/Day09.kt b/src/main/kotlin/no/rodland/advent_2023/Day09.kt index 93e0dfad..7f3036a2 100644 --- a/src/main/kotlin/no/rodland/advent_2023/Day09.kt +++ b/src/main/kotlin/no/rodland/advent_2023/Day09.kt @@ -5,24 +5,37 @@ import no.rodland.advent.Day // template generated: 09/12/2023 // Fredrik Rødland 2023 -class Day09(val input: List) : Day>> { + +// can probably be calculated directly (think something along the lines of Pascal's Triangle) +// instead of looping through everything (twice for part 2) +class Day09(val input: List) : Day>> { private val parsed = input.parse() override fun partOne(): Int { - return parsed.sumOf { diffList(it) } + return parsed.sumOf { list -> allDiffs(list).sumOf { it.last() } } } - override fun partTwo(): Long { - return 2 + override fun partTwo(): Int { + return parsed.sumOf { list -> + val append2 = mutableListOf>() + allDiffs(list).reversed().map { next -> + append2.add(diffFirst(append2.lastOrNull(), next)) + } + append2.last().first() + } } - private fun diffList(list: List): Int { + private fun allDiffs(list: List): List> { val append = mutableListOf(list) while (append.last().any { it != 0 }) { append.add(append.last().diffs()) } - return append.sumOf { it.last() } + return append + } + + private fun diffFirst(last: List?, next: List): List { + return listOf(next.first() - (last?.first() ?: 0)) + next } private fun List.diffs(): List = windowed(2) { it.last() - it.first() } diff --git a/src/test/kotlin/no/rodland/advent_2023/Day09Test.kt b/src/test/kotlin/no/rodland/advent_2023/Day09Test.kt index 43e42f8e..095d6fa2 100644 --- a/src/test/kotlin/no/rodland/advent_2023/Day09Test.kt +++ b/src/test/kotlin/no/rodland/advent_2023/Day09Test.kt @@ -16,9 +16,9 @@ internal class Day09Test { ) private val resultTestOne = 114 - private val resultTestTwo = 2L + private val resultTestTwo = 2 private val resultOne = 1972648895 - private val resultTwo = 2L + private val resultTwo = 919 val test = defaultTestSuiteParseOnInit( Day09(data09),