Skip to content

Commit

Permalink
2023 - Day09 - part 2 - can probably be calculated directly (think so…
Browse files Browse the repository at this point in the history
…mething along the lines of Pascal's Triangle) instead of looping through everything (twice for part 2)
  • Loading branch information
fmmr committed Dec 9, 2023
1 parent ea1a031 commit 13804c5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
25 changes: 19 additions & 6 deletions src/main/kotlin/no/rodland/advent_2023/Day09.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,37 @@ import no.rodland.advent.Day
// template generated: 09/12/2023
// Fredrik Rødland 2023

class Day09(val input: List<String>) : Day<Int, Long, List<List<Int>>> {

// 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<String>) : Day<Int, Int, List<List<Int>>> {

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<List<Int>>()
allDiffs(list).reversed().map { next ->
append2.add(diffFirst(append2.lastOrNull(), next))
}
append2.last().first()
}
}

private fun diffList(list: List<Int>): Int {
private fun allDiffs(list: List<Int>): List<List<Int>> {
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<Int>?, next: List<Int>): List<Int> {
return listOf(next.first() - (last?.first() ?: 0)) + next
}

private fun List<Int>.diffs(): List<Int> = windowed(2) { it.last() - it.first() }
Expand Down
4 changes: 2 additions & 2 deletions src/test/kotlin/no/rodland/advent_2023/Day09Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit 13804c5

Please sign in to comment.