Day 11 (Make fast when hot)
This commit is contained in:
@@ -11,28 +11,26 @@ object Day11 extends Solver(11):
|
|||||||
val mod = Math.pow(10, numDigits / 2).toLong
|
val mod = Math.pow(10, numDigits / 2).toLong
|
||||||
Some(n % mod, n / mod)
|
Some(n % mod, n / mod)
|
||||||
|
|
||||||
private def count(initial: Seq[Long], depth: Int): Long =
|
private val memo = MuMap.empty[(Long, Int), Long]
|
||||||
def step(stones: MuMap[Long, Long]): MuMap[Long, Long] =
|
private def count(initial: Long, numBlinks: Int): Long =
|
||||||
val next = MuMap.empty[Long, Long].withDefaultValue(0L)
|
def rec(stone: Long, blinks: Int): Long =
|
||||||
for ((stone, count) <- stones) {
|
if blinks == 0 then return 1L
|
||||||
if stone == 0 then next(1) += count
|
memo.getOrElseUpdate(
|
||||||
else
|
(stone, blinks), {
|
||||||
halves(stone) match
|
if stone == 0 then rec(1L, blinks - 1)
|
||||||
case Some((a, b)) =>
|
else
|
||||||
next(a) += count
|
halves(stone) match
|
||||||
next(b) += count
|
case Some(a, b) =>
|
||||||
case None =>
|
rec(a, blinks - 1) + rec(b, blinks - 1)
|
||||||
next(stone * 2024) += count
|
case None => rec(stone * 2024, blinks - 1)
|
||||||
}
|
}
|
||||||
next
|
)
|
||||||
|
rec(initial, numBlinks)
|
||||||
val initMap = MuMap.from(initial.map((_, 1L)))
|
|
||||||
Seq.iterate(initMap, depth + 1)(step).last.values.sum
|
|
||||||
|
|
||||||
def run(input: os.ReadablePath): (Timings, Solution) =
|
def run(input: os.ReadablePath): (Timings, Solution) =
|
||||||
val (pre_time, in) = timed { longs(os.read.lines(input).head) }
|
val (pre_time, in) = timed { longs(os.read.lines(input).head) }
|
||||||
val (p1_time, p1_solution) = timed { count(in, 25) }
|
val (p1_time, p1_solution) = timed { in.map(v => count(v, 25)).sum }
|
||||||
val (p2_time, p2_solution) = timed { count(in, 75) }
|
val (p2_time, p2_solution) = timed { in.map(v => count(v, 75)).sum }
|
||||||
|
|
||||||
(
|
(
|
||||||
Timings(pre_time, p1_time, p2_time),
|
Timings(pre_time, p1_time, p2_time),
|
||||||
|
|||||||
Reference in New Issue
Block a user