This commit is contained in:
Christian
2024-12-22 17:44:41 +01:00
parent 6db15ba9af
commit 843bfcb2c3
4 changed files with 2066 additions and 1 deletions

View File

@@ -23,7 +23,8 @@ val solvers = Map[Int, Solver](
18 -> Day18,
19 -> Day19,
20 -> Day20,
21 -> Day21
21 -> Day21,
22 -> Day22
)
def runSolver(solver: Solver, input: os.Path): Unit =

View File

@@ -0,0 +1,60 @@
package dev.ctsk.aoc.days
import dev.ctsk.aoc.*
import scala.collection.mutable
object Day22 extends Solver(22):
inline def hash(n: Long): Long =
var secret = n
secret ^= (secret << 6)
secret &= 0xffffff
secret ^= (secret >> 5)
secret &= 0xffffff
secret ^= (secret << 11)
secret &= 0xffffff
secret
def hash(n: Long, count: Int): Long =
Iterator.iterate(n)(hash).drop(count).next()
def part1(initial: Seq[Long]): Long = initial.map(hash(_, 2000)).sum
def part2(initial: Seq[Long]): Long =
inline def update(hash: Int, next: Int): Int =
((hash << 5) & 0xfffff) | (next + 10)
val maxHash = Seq(9, 9, 9, 9).fold(0)(update)
val bananas = Array.fill(maxHash)(0)
val seen = mutable.BitSet(maxHash)
initial.foreach { value =>
seen.clear()
val it = Iterator.iterate(value)(hash).map(_.toInt % 10)
var last = it.next()
var window = 0
for v <- it.take(3) do
val diff = v - last
last = v
window = update(window, diff)
for v <- it.take(2000 - 3) do
val diff = v - last
last = v
window = update(window, diff)
if !seen(window) then
seen += window
bananas(window) += v
}
bananas.max
override def run(input: os.ReadablePath): (Timings, Solution) =
val initial = os.read.lines(input).map(_.toLong)
val (p1_time, p1_solution) = timed { part1(initial) }
val (p2_time, p2_solution) = timed { part2(initial) }
(
Timings(0, p1_time, p2_time),
Solution(Long.box(p1_solution), Long.box(p2_solution))
)

2
data/22.ans Normal file
View File

@@ -0,0 +1,2 @@
16894083306
1925

2002
data/22.in Normal file

File diff suppressed because it is too large Load Diff