diff --git a/src/day09.scala b/src/day09.scala index 2154a4b..e1cbc10 100644 --- a/src/day09.scala +++ b/src/day09.scala @@ -11,25 +11,20 @@ val dayNumber = "09" @main def part2: Unit = println(part2(loadInput(dayNumber))) -@tailrec def generateDifferences(acc: Array[Array[Long]]): Array[Array[Long]] = - if acc.last.forall(_ == 0) then acc - else - generateDifferences( - acc.appended( - acc.last.sliding(2).map { case Array(l, r) => r - l }.toArray +def findNextValue(history: Array[Long]): Long = + @tailrec def aux(history: Array[Long], acc: Long): Long = + if history.forall(_ == 0) then acc + else + aux( + history.sliding(2).map { case Array(l, r) => r - l }.toArray, + acc + history.last ) - ) + aux(history, 0) def part1(input: String): String = val readings = input.split('\n').map(_.split(' ').map(_.toLong)) - def findNextValue(history: Array[Long]): Long = - generateDifferences(Array(history)).map(_.last).sum readings.map(findNextValue).sum.toString def part2(input: String): String = val readings = input.split('\n').map(_.split(' ').map(_.toLong)) - def findPreviousValue(history: Array[Long]): Long = - generateDifferences(Array(history)) - .map(_.head) - .reduceRight((v, acc) => v - acc) - readings.map(findPreviousValue).sum.toString + readings.map(_.reverse).map(findNextValue).sum.toString