Day 09 simpler
This commit is contained in:
parent
e1a8169fd2
commit
97e472a693
1 changed files with 9 additions and 14 deletions
|
|
@ -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
|
||||
def findNextValue(history: Array[Long]): Long =
|
||||
@tailrec def aux(history: Array[Long], acc: Long): Long =
|
||||
if history.forall(_ == 0) then acc
|
||||
else
|
||||
generateDifferences(
|
||||
acc.appended(
|
||||
acc.last.sliding(2).map { case Array(l, r) => r - l }.toArray
|
||||
)
|
||||
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue