Skip to content

Commit 2eae311

Browse files
committed
Solve 2025 day 4 part 2
1 parent d11c8a9 commit 2eae311

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,30 @@ import eu.sim642.adventofcodelib.pos.Pos
66

77
object Day4 {
88

9-
def countAccessibleRolls(grid: Grid[Char]): Int = {
9+
// TODO: make this more like cellular automaton?
10+
def accessibleRolls(grid: Grid[Char]): Seq[Pos] = {
1011
(for {
1112
(row, y) <- grid.view.zipWithIndex
1213
(cell, x) <- row.view.zipWithIndex
1314
pos = Pos(x, y)
1415
if grid(pos) == '@'
1516
neighbors = Pos.allOffsets.map(pos + _).filter(grid.containsPos)
1617
if neighbors.count(grid(_) == '@') < 4
17-
} yield pos).size
18+
} yield pos).toSeq
19+
}
20+
21+
def countAccessibleRolls(grid: Grid[Char]): Int = {
22+
accessibleRolls(grid).size
23+
}
24+
25+
def countRemovableRolls(grid: Grid[Char]): Int = {
26+
val accessible = accessibleRolls(grid)
27+
if (accessible.isEmpty)
28+
0
29+
else {
30+
val newGrid = accessible.foldLeft(grid)(_.updatedGrid(_, '.'))
31+
accessible.size + countRemovableRolls(newGrid)
32+
}
1833
}
1934

2035
def parseGrid(input: String): Grid[Char] = input.linesIterator.map(_.toVector).toVector
@@ -23,5 +38,6 @@ object Day4 {
2338

2439
def main(args: Array[String]): Unit = {
2540
println(countAccessibleRolls(parseGrid(input)))
41+
println(countRemovableRolls(parseGrid(input)))
2642
}
2743
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,12 @@ class Day4Test extends AnyFunSuite {
2424
test("Part 1 input answer") {
2525
assert(countAccessibleRolls(parseGrid(input)) == 1527)
2626
}
27+
28+
test("Part 2 examples") {
29+
assert(countRemovableRolls(parseGrid(exampleInput)) == 43)
30+
}
31+
32+
test("Part 2 input answer") {
33+
assert(countRemovableRolls(parseGrid(input)) == 8690)
34+
}
2735
}

0 commit comments

Comments
 (0)