From f9f5540725a589862d5e00a431c4fd66e3452f33 Mon Sep 17 00:00:00 2001 From: Simmo Saan Date: Sat, 9 Dec 2023 09:46:40 +0200 Subject: [PATCH] Solve 2023 day 9 part 2 --- .../scala/eu/sim642/adventofcode2023/Day9.scala | 14 ++++++++++++++ .../eu/sim642/adventofcode2023/Day9Test.scala | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/main/scala/eu/sim642/adventofcode2023/Day9.scala b/src/main/scala/eu/sim642/adventofcode2023/Day9.scala index 41049147..9df3e07a 100644 --- a/src/main/scala/eu/sim642/adventofcode2023/Day9.scala +++ b/src/main/scala/eu/sim642/adventofcode2023/Day9.scala @@ -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 @@ -24,5 +37,6 @@ object Day9 { def main(args: Array[String]): Unit = { println(sumNextValues(parseHistories(input))) + println(sumPrevValues(parseHistories(input))) } } diff --git a/src/test/scala/eu/sim642/adventofcode2023/Day9Test.scala b/src/test/scala/eu/sim642/adventofcode2023/Day9Test.scala index b663f76b..d9d8ee65 100644 --- a/src/test/scala/eu/sim642/adventofcode2023/Day9Test.scala +++ b/src/test/scala/eu/sim642/adventofcode2023/Day9Test.scala @@ -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) + } }