@@ -9,69 +9,63 @@ class Day07 @Inject constructor(
99 private val generatorFactory : InputGeneratorFactory ,
1010) {
1111 fun partOne (filename : String ) = generatorFactory.forFile(filename).read { input ->
12- var beamIndices = mutableSetOf<Int >()
12+ val beamIndices = mutableSetOf<Int >()
1313 val manifold = mutableListOf<MutableList <Char >>()
1414
1515 input.forEachIndexed { index, line ->
16- if (index == 0 ) beamIndices.add(line.indexOf(' S' ))
16+ if (index == 0 ) { beamIndices.add(line.indexOf(' S' )) }
1717 manifold.add(line.toCharArray().toMutableList())
1818 }
1919
2020 var depth = 1
2121 var splits = 0
2222 while (depth < manifold.size) {
23- val updateBeamIndices = mutableSetOf<Int >()
2423 val line = manifold[depth]
2524
26- beamIndices.forEach { beamIndex ->
25+ beamIndices.toList(). also { beamIndices.clear() }. forEach { beamIndex ->
2726 if (line[beamIndex] == ' ^' ) {
2827 splits++
29- updateBeamIndices .add(beamIndex - 1 )
30- updateBeamIndices .add(beamIndex + 1 )
28+ beamIndices .add(beamIndex - 1 )
29+ beamIndices .add(beamIndex + 1 )
3130 } else {
32- updateBeamIndices .add(beamIndex)
31+ beamIndices .add(beamIndex)
3332 }
3433 }
3534
36- beamIndices = updateBeamIndices
3735 depth++
3836 }
3937
4038 splits
4139 }
4240
4341 fun partTwo (filename : String ) = generatorFactory.forFile(filename).read { input ->
44- var beams = mutableMapOf<Location , Long >()
42+ val beams = mutableMapOf<Location , Long >().withDefault { 0 }
4543 val manifold = mutableListOf<MutableList <Char >>()
4644
4745 input.forEachIndexed { index, line ->
48- if (index == 0 ) {
49- beams[Location (0 , line.indexOf(' S' ))] = 1
50- }
46+ if (index == 0 ) { beams[Location (0 , line.indexOf(' S' ))] = 1 }
5147 manifold.add(line.toCharArray().toMutableList())
5248 }
5349
5450 var depth = 1
5551 while (depth < manifold.size) {
56- val newBeams = mutableMapOf<Location , Long >().withDefault { 0 }
5752 val line = manifold[depth]
5853
59- beams.forEach { (location, count) ->
54+ beams.toList(). also { beams.clear() }. forEach { (location, count) ->
6055 if (location.depth != depth - 1 ) { throw IllegalStateException (" We should only be tracking the last row." ) }
6156
6257 if (line[location.index] == ' ^' ) {
6358 val left = Location (depth, location.index - 1 )
6459 val right = Location (depth, location.index + 1 )
6560
66- newBeams [left] = newBeams .getValue(left) + count
67- newBeams [right] = newBeams .getValue(right) + count
61+ beams [left] = beams .getValue(left) + count
62+ beams [right] = beams .getValue(right) + count
6863 } else {
6964 val below = Location (depth, location.index)
70- newBeams [below] = newBeams .getValue(below) + count
65+ beams [below] = beams .getValue(below) + count
7166 }
7267 }
7368
74- beams = newBeams
7569 depth++
7670 }
7771
0 commit comments