Skip to content

Commit 1d9cb46

Browse files
committed
Solve 2025 day 7 part 2
1 parent 82ce962 commit 1d9cb46

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/main/scala/eu/sim642/adventofcode2025/Day7.scala

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import eu.sim642.adventofcodelib.GridImplicits.*
55
import eu.sim642.adventofcodelib.graph.{BFS, GraphTraversal, UnitNeighbors}
66
import eu.sim642.adventofcodelib.pos.Pos
77

8+
import scala.annotation.tailrec
9+
810
object Day7 {
911

1012
private val cellOffsets = Map(
@@ -27,11 +29,36 @@ object Day7 {
2729
.count(pos => grid(pos) == '^')
2830
}
2931

32+
def countTimelines(grid: Grid[Char]): Long = {
33+
34+
@tailrec
35+
def helper(y: Int, xs: Map[Int, Long]): Long = {
36+
if (y >= grid.size)
37+
xs.values.sum
38+
else {
39+
val newXs =
40+
(for {
41+
(x, count) <- xs.view
42+
pos = Pos(x, y)
43+
offset <- cellOffsets(grid(pos))
44+
newPos = pos + offset
45+
} yield newPos.x -> count).groupMapReduce(_._1)(_._2)(_ + _)
46+
47+
helper(y + 1, newXs)
48+
}
49+
}
50+
51+
helper(0, Map(grid.posOf('S').x -> 1))
52+
}
53+
3054
def parseGrid(input: String): Grid[Char] = input.linesIterator.map(_.toVector).toVector
3155

3256
lazy val input: String = scala.io.Source.fromInputStream(getClass.getResourceAsStream("day7.txt")).mkString.trim
3357

3458
def main(args: Array[String]): Unit = {
3559
println(countBeamSplits(parseGrid(input)))
60+
println(countTimelines(parseGrid(input)))
61+
62+
// part 2: 2012790981 (Int overflowed in countTimelines)
3663
}
3764
}

src/test/scala/eu/sim642/adventofcode2025/Day7Test.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,12 @@ class Day7Test extends AnyFunSuite {
3030
test("Part 1 input answer") {
3131
assert(countBeamSplits(parseGrid(input)) == 1587)
3232
}
33+
34+
test("Part 2 examples") {
35+
assert(countTimelines(parseGrid(exampleInput)) == 40)
36+
}
37+
38+
test("Part 2 input answer") {
39+
assert(countTimelines(parseGrid(input)) == 5748679033029L)
40+
}
3341
}

0 commit comments

Comments
 (0)