advent-of-code-2024/06-a.kts

79 lines
1.8 KiB
Text
Raw Normal View History

2024-12-06 15:24:24 +08:00
import java.util.Scanner
enum class Direction {
NORTH {
override fun moveFrom(row: Int, col: Int): Pair<Int, Int> {
return Pair(row-1, col)
}
}, SOUTH {
override fun moveFrom(row: Int, col: Int): Pair<Int, Int> {
return Pair(row+1, col)
}
}, WEST {
override fun moveFrom(row: Int, col: Int): Pair<Int, Int> {
return Pair(row, col-1)
}
}, EAST {
override fun moveFrom(row: Int, col: Int): Pair<Int, Int> {
return Pair(row, col+1)
}
};
fun turnRight(): Direction {
return when (this) {
NORTH -> EAST
EAST -> SOUTH
SOUTH -> WEST
WEST -> NORTH
}
}
abstract fun moveFrom(row: Int, col: Int): Pair<Int, Int>
}
val scanner = Scanner(System.`in`)
val map = ArrayList<Array<Char>>()
var rows = 0
var guardRow = -1
var guardCol = -1
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
val pos = line.indexOf('^')
if (pos != -1) {
guardRow = rows
guardCol = pos
}
val chars = line.toCharArray().toTypedArray()
map.add(chars)
rows++
}
var facing = Direction.NORTH
var visitedCount = 0
walk@ while (true) {
if (map[guardRow][guardCol] != 'X') {
visitedCount++
}
map[guardRow][guardCol] = 'X'
var seeking = true
do {
val (nextRow, nextCol) = facing.moveFrom(guardRow, guardCol)
if (nextRow < 0 || nextRow >= map.size || nextCol < 0 || nextCol >= map[nextCol].size) {
break@walk
}
if (map[nextRow][nextCol] == '#') {
facing = facing.turnRight()
} else {
guardRow = nextRow
guardCol = nextCol
seeking = false
}
} while (seeking)
}
println(visitedCount)