Skip to content

Commit

Permalink
Solve 2023 day 9 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 9, 2023
1 parent 125176e commit f9f5540
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2023/Day9.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ object Day9 {

def sumNextValues(histories: Seq[History]): Int = histories.map(nextValue).sum

def prevValue(history: History): Int = {
// TODO: deduplicate
val differences = LazyList.iterate(history)(history =>
(history lazyZip history.tail).map(-_ + _)
)
val nonZeroDifferences = differences.takeWhile(!_.forall(_ == 0))
nonZeroDifferences
.map(_.head)
.foldRight(0)((a, b) => a - b)
}

def sumPrevValues(histories: Seq[History]): Int = histories.map(prevValue).sum


def parseHistories(input: String): Seq[History] =
input.linesIterator.map(_.split(' ').map(_.toInt).toSeq).toSeq
Expand All @@ -24,5 +37,6 @@ object Day9 {

def main(args: Array[String]): Unit = {
println(sumNextValues(parseHistories(input)))
println(sumPrevValues(parseHistories(input)))
}
}
12 changes: 12 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day9Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,16 @@ class Day9Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(sumNextValues(parseHistories(input)) == 1708206096)
}

test("Part 2 examples") {
val histories = parseHistories(exampleInput)

assert(prevValue(histories(0)) == -3)
assert(prevValue(histories(1)) == 0)
assert(prevValue(histories(2)) == 5)
}

test("Part 2 input answer") {
assert(sumPrevValues(parseHistories(input)) == 1050)
}
}

0 comments on commit f9f5540

Please sign in to comment.