@@ -7,7 +7,6 @@ import com.cluddles.aoc.util.CharGrid
77import com.cluddles.aoc.util.Dir4
88import com.cluddles.aoc.util.Grid
99import com.cluddles.aoc.util.MutableGrid
10- import kotlin.text.iterator
1110
1211/* * Warehouse Woes */
1312object Day15: Solver<Day15.Input, Int> {
@@ -20,44 +19,33 @@ object Day15: Solver<Day15.Input, Int> {
2019 const val BOX_L = ' ['
2120 const val BOX_R = ' ]'
2221
23- data class Input (val grid : Grid <Char >, val moves : String )
22+ data class Input (val grid : Grid <Char >, val moves : List < Dir4 > )
2423
2524 data class Robot (var x : Int , var y : Int )
2625
2726 override fun prepareInput (src : SolverInput ): Input {
28- val gridLines = mutableListOf<String >()
29- val it = src.lines(allowBlankLines = true ).iterator()
30- while (it.hasNext()) {
31- val l = it.next()
32- if (l.isNotBlank()) {
33- gridLines.add(l)
34- } else {
35- break
36- }
37- }
38-
39- val moves = StringBuffer ()
40- while (it.hasNext()) {
41- val l = it.next()
42- moves.append(l.trimEnd())
43- }
44-
45- return Input (CharGrid (gridLines), moves.toString())
27+ val gridLines = src.lines(allowBlankLines = true )
28+ .takeWhile { it.isNotBlank() }
29+ .toList()
30+ val moves = src.lines(allowBlankLines = true )
31+ .dropWhile { it.isNotBlank() }
32+ .dropWhile { it.isBlank() }
33+ .flatMap { it.map { ch -> Dir4 .fromChar(ch) } }
34+ .toList()
35+ return Input (CharGrid (gridLines), moves)
4636 }
4737
4838 private fun findRobot (grid : Grid <Char >): Robot {
4939 return grid.iterableWithPos().firstOrNull { it.data == ROBOT }?.let { Robot (it.x, it.y) }
5040 ? : error(" No robot found" )
5141 }
5242
53- private fun applyMove (robot : Robot , move : Char , grid : MutableGrid <Char >) {
54- val dir = Dir4 .fromChar(move)
43+ private fun applyMove (robot : Robot , dir : Dir4 , grid : MutableGrid <Char >) {
5544 if (canMove(grid, robot.x + dir.x, robot.y + dir.y, dir)) {
5645 grid[robot.x, robot.y] = BLANK
57- if (dir.x != 0 ) {
58- pushX(grid, robot.x + dir.x, robot.y, dir.x)
59- } else {
60- pushY(grid, robot.x, robot.y + dir.y, dir.y)
46+ when (dir.y) {
47+ 0 -> pushX(grid, robot.x + dir.x, robot.y, dir.x)
48+ else -> pushY(grid, robot.x, robot.y + dir.y, dir.y)
6149 }
6250 robot.x + = dir.x
6351 robot.y + = dir.y
@@ -111,16 +99,12 @@ object Day15: Solver<Day15.Input, Int> {
11199 }
112100 }
113101
114- private fun gps (grid : Grid <Char >): Int {
115- return grid.iterableWithPos().sumOf { if (it.data == BOX || it.data == BOX_L ) it.x + it.y * 100 else 0 }
116- }
117-
118- private fun solve (grid : MutableGrid <Char >, moves : String ): Int {
102+ private fun solve (grid : MutableGrid <Char >, moves : List <Dir4 >): Int {
119103 val robot = findRobot(grid)
120104 for (m in moves) {
121105 applyMove(robot, m, grid)
122106 }
123- return gps( grid)
107+ return grid.iterableWithPos().sumOf { if (it.data == BOX || it.data == BOX_L ) it.x + it.y * 100 else 0 }
124108 }
125109
126110 override fun solvePart1 (input : Input ): Int {
0 commit comments