Skip to content

Commit 14b610f

Browse files
committed
day 11 part 2 solution
1 parent db61e75 commit 14b610f

File tree

1 file changed

+35
-3
lines changed
  • day11/src/main/kotlin/org/adventofcode

1 file changed

+35
-3
lines changed

day11/src/main/kotlin/org/adventofcode/App.kt

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ fun EnergyLevel.step(): EnergyLevel {
1919
}
2020
}
2121

22-
fun Point.toMinimalString(): String {
22+
fun Point.toCompactString(): String {
2323
return "($row, $col)"
2424
}
2525

@@ -41,6 +41,12 @@ fun EnergyGrid.findAllPointsNeighboring(p: Point): List<Point> {
4141
}.flatten().filterNotNull()
4242
}
4343

44+
fun EnergyGrid.entryCount(): Int {
45+
val rowCount = this.size
46+
if (rowCount == 0) return 0
47+
return rowCount * this[0].size
48+
}
49+
4450
fun EnergyGrid.map(fn: ((Point, EnergyLevel) -> EnergyLevel)? = null): EnergyGrid {
4551
return this.mapIndexed { rowIdx, rowData ->
4652
rowData.mapIndexed { colIdx, energyLevel ->
@@ -142,7 +148,7 @@ fun Simulation.step(): SimulationStepResult {
142148
}
143149

144150
fun runSoluationPart1(energyGrid: EnergyGrid, stepCount: Int = 10) {
145-
println("Day 11 Solution: Part1\n")
151+
println("Day 11 Solution: Part 1\n")
146152

147153
var initSimulation = Simulation(energyGrid)
148154
val initStep = Triple(0, initSimulation, 0)
@@ -162,10 +168,36 @@ fun runSoluationPart1(energyGrid: EnergyGrid, stepCount: Int = 10) {
162168
println("Total flashes: $totalFlashes")
163169
}
164170

171+
fun runSolutionPart2(energyGrid: EnergyGrid) {
172+
println("Day 11 Solution: Part 2\n")
173+
174+
var initSimulation = Simulation(energyGrid)
175+
val initStep = Triple(0, initSimulation, -1)
176+
177+
val stepGenerator = generateSequence(initStep) { (step, simulation, prevFlashCount) ->
178+
if (prevFlashCount == simulation.grid.entryCount()) {
179+
null
180+
} else {
181+
val result = simulation.step()
182+
Triple(step + 1, result.simulation, result.flashedPoints.size)
183+
}
184+
}
185+
186+
val steps = stepGenerator.toList()
187+
188+
steps.forEach { (step, simulation, flashCount) ->
189+
println("After step $step")
190+
simulation.grid.prettyPrint()
191+
println()
192+
}
193+
}
194+
195+
165196
fun main() {
166-
val energyGrid = File("day11/src/main/resources/puzzleInput.txt")
197+
val energyGrid = File("day11/src/main/resources/sampleInput.txt")
167198
.readLines()
168199
.map { it.toList().map { c -> c.digitToInt() } }
169200

170201
runSoluationPart1(energyGrid, 100)
202+
// runSolutionPart2(energyGrid)
171203
}

0 commit comments

Comments
 (0)