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 =
|
@main def part2: Unit =
|
||||||
println(part2(loadInput(dayNumber)))
|
println(part2(loadInput(dayNumber)))
|
||||||
|
|
||||||
@tailrec def generateDifferences(acc: Array[Array[Long]]): Array[Array[Long]] =
|
def findNextValue(history: Array[Long]): Long =
|
||||||
if acc.last.forall(_ == 0) then acc
|
@tailrec def aux(history: Array[Long], acc: Long): Long =
|
||||||
|
if history.forall(_ == 0) then acc
|
||||||
else
|
else
|
||||||
generateDifferences(
|
aux(
|
||||||
acc.appended(
|
history.sliding(2).map { case Array(l, r) => r - l }.toArray,
|
||||||
acc.last.sliding(2).map { case Array(l, r) => r - l }.toArray
|
acc + history.last
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
aux(history, 0)
|
||||||
|
|
||||||
def part1(input: String): String =
|
def part1(input: String): String =
|
||||||
val readings = input.split('\n').map(_.split(' ').map(_.toLong))
|
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
|
readings.map(findNextValue).sum.toString
|
||||||
|
|
||||||
def part2(input: String): String =
|
def part2(input: String): String =
|
||||||
val readings = input.split('\n').map(_.split(' ').map(_.toLong))
|
val readings = input.split('\n').map(_.split(' ').map(_.toLong))
|
||||||
def findPreviousValue(history: Array[Long]): Long =
|
readings.map(_.reverse).map(findNextValue).sum.toString
|
||||||
generateDifferences(Array(history))
|
|
||||||
.map(_.head)
|
|
||||||
.reduceRight((v, acc) => v - acc)
|
|
||||||
readings.map(findPreviousValue).sum.toString
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue