Skip to content

Commit

Permalink
Add some grid utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
tschut committed Dec 11, 2023
1 parent dbfa26d commit 9619b2b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/main/kotlin/nl/tiemenschut/aoc/lib/util/grid/Grid.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package nl.tiemenschut.aoc.lib.util.grid

import nl.tiemenschut.aoc.lib.util.points.Point
import nl.tiemenschut.aoc.lib.util.points.by

class Grid<T>(val data: List<MutableList<T>>) {
fun width() = data.size
fun height() = data[0].size

fun allIndexOff(value: T) = (0..<width()).flatMap { x ->
(0..<height()).mapNotNull { y ->
if (get(x by y) == value) x by y else null
}
}

operator fun get(p: Point<Int>) = data[p.x][p.y]

operator fun set(p: Point<Int>, value: T) {
data[p.x][p.y] = value
}

override fun toString() = buildString {
for (y in 0..<height()) {
for (x in 0..<width()) {
append(get(x by y))
}
appendLine()
}
}


}
19 changes: 19 additions & 0 deletions src/main/kotlin/nl/tiemenschut/aoc/lib/util/grid/GridParser.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package nl.tiemenschut.aoc.lib.util.grid

import nl.tiemenschut.aoc.lib.dsl.parser.InputParser

object CharGridParser : InputParser<Grid<Char>> {
override fun parse(input: String): Grid<Char> {
val lines = input.split("\n")

val data = List(lines[0].length) { MutableList(lines.size) { ' ' } }.also { grid ->
for (y in lines.indices) {
for (x in lines[y].indices) {
grid[x][y] = lines[y][x]
}
}
}

return Grid(data)
}
}

0 comments on commit 9619b2b

Please sign in to comment.