Day 15 part 1
This commit is contained in:
parent
dbcf8c228f
commit
3f2ab90e6f
3 changed files with 134 additions and 0 deletions
|
@ -16,6 +16,14 @@ operator fun <T> Grid<T>.set(coordinate: Grid.Coordinate, value: T) = set(coordi
|
|||
operator fun <T> Grid<T>.get(coordinate: Grid.Coordinate) = get(coordinate.x, coordinate.y)
|
||||
operator fun <T> Grid<T>.contains(coordinate: Grid.Coordinate) = inside(coordinate)
|
||||
|
||||
fun <T> Grid<T>.coordinates() = sequence {
|
||||
for (y in 0..<height) {
|
||||
for (x in 0..<width) {
|
||||
yield(Grid.Coordinate(x, y))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ListGrid<T>(override val width: Int, override val height: Int, content: List<T>) : Grid<T> {
|
||||
init {
|
||||
assert(width * height == content.count())
|
||||
|
|
55
2024/src/main/kotlin/day15.kt
Normal file
55
2024/src/main/kotlin/day15.kt
Normal file
|
@ -0,0 +1,55 @@
|
|||
fun main() {
|
||||
val iterator = readInput("day15.txt").iterator()
|
||||
val input = Sequence { iterator }
|
||||
|
||||
val grid = CharGrid(input.takeWhile { it.isNotEmpty() }.toList())
|
||||
var robot = grid.find('@')!!
|
||||
|
||||
val program = input.flatMap { line ->
|
||||
line.map {
|
||||
when (it) {
|
||||
'^' -> Direction.North
|
||||
'>' -> Direction.East
|
||||
'v' -> Direction.South
|
||||
'<' -> Direction.West
|
||||
else -> error("Invalid direction $it")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
grid[robot] = '.'
|
||||
for (direction in program) {
|
||||
val next = robot.step(direction)
|
||||
if (grid.push(next, direction)) {
|
||||
robot = next
|
||||
}
|
||||
}
|
||||
|
||||
val part1 = grid.coordinates()
|
||||
.filter { grid[it] == 'O' }
|
||||
.fold(0) { acc, coord ->
|
||||
acc + coord.x + 100 * coord.y
|
||||
}
|
||||
|
||||
println("Part 1: $part1")
|
||||
}
|
||||
|
||||
fun CharGrid.push(position: Grid.Coordinate, direction: Direction): Boolean {
|
||||
if (this[position] == '.') {
|
||||
return true
|
||||
}
|
||||
|
||||
var next = position
|
||||
while (this[next] == 'O') {
|
||||
next = next.step(direction)
|
||||
}
|
||||
|
||||
if (this[next] == '#') {
|
||||
return false
|
||||
}
|
||||
|
||||
this[next] = 'O'
|
||||
this[position] = '.'
|
||||
|
||||
return true
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue