Day 09 simpler

This commit is contained in:
Paul-Henri Froidmont 2023-12-09 15:36:34 +01:00
parent e1a8169fd2
commit 97e472a693
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE

View file

@ -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