Skip to content

Commit

Permalink
Add naive solution to 2023 day 21 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 21, 2023
1 parent 880a4ed commit 43c0e21
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2023/Day21.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import eu.sim642.adventofcodelib.Grid
import eu.sim642.adventofcodelib.GridImplicits.*
import eu.sim642.adventofcodelib.graph.{GraphSearch, SimultaneousBFS, UnitNeighbors}
import eu.sim642.adventofcodelib.pos.Pos
import eu.sim642.adventofcodelib.IntegralImplicits._

object Day21 {

Expand All @@ -27,11 +28,37 @@ object Day21 {
SimultaneousBFS.search(graphSearch).distances.count(_._2 % 2 == steps % 2)
}

// copied from 2021 day 25
extension (pos: Pos) {
def %+(other: Pos): Pos = Pos(pos.x %+ other.x, pos.y %+ other.y)
}

def countReachableExactlyInfinite(grid: Grid[Char], steps: Int = 26501365): Int = {
val gridSize = Pos(grid(0).size, grid.size)

val graphSearch = new GraphSearch[Pos] with UnitNeighbors[Pos] {
override val startNode: Pos = grid.posOf('S')

override def unitNeighbors(pos: Pos): IterableOnce[Pos] = {
for {
offset <- Pos.axisOffsets
newPos = pos + offset
if grid(newPos %+ gridSize) != '#'
} yield newPos
}

override def isTargetNode(pos: Pos, dist: Int): Boolean = dist == steps
}

SimultaneousBFS.search(graphSearch).distances.count(_._2 % 2 == steps % 2)
}

def parseGrid(input: String): Grid[Char] = input.linesIterator.map(_.toVector).toVector

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

def main(args: Array[String]): Unit = {
println(countReachableExactly(parseGrid(input)))
println(countReachableExactlyInfinite(parseGrid(input)))
}
}
14 changes: 14 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day21Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,18 @@ class Day21Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(countReachableExactly(parseGrid(input)) == 3687)
}

test("Part 2 examples") {
assert(countReachableExactlyInfinite(parseGrid(exampleInput), 6) == 16)
assert(countReachableExactlyInfinite(parseGrid(exampleInput), 10) == 50)
assert(countReachableExactlyInfinite(parseGrid(exampleInput), 50) == 1594)
assert(countReachableExactlyInfinite(parseGrid(exampleInput), 100) == 6536)
assert(countReachableExactlyInfinite(parseGrid(exampleInput), 500) == 167004)
//assert(countReachableExactlyInfinite(parseGrid(exampleInput), 1000) == 668697)
//assert(countReachableExactlyInfinite(parseGrid(exampleInput), 5000) == 16733044)
}

test("Part 2 input answer") {
//assert(countReachableExactlyInfinite(parseGrid(input)) == 3687)
}
}

0 comments on commit 43c0e21

Please sign in to comment.