diff --git a/2024/src/main/kotlin/CharGrid.kt b/2024/src/main/kotlin/CharGrid.kt index 3a4b0b9..8a32f66 100644 --- a/2024/src/main/kotlin/CharGrid.kt +++ b/2024/src/main/kotlin/CharGrid.kt @@ -1,7 +1,11 @@ -class CharGrid(val rows: List) : Grid { +class CharGrid(rows: List) : Grid { + val rows = rows.toMutableList() override val width = rows.firstOrNull()?.count() ?: 0 override val height get() = rows.count() + constructor(width: Int, height: Int, char: Char) + : this((1..height).map { char.toString().repeat(width) }) + init { assert(rows.all { it.length == width }) } @@ -75,4 +79,8 @@ class CharGrid(val rows: List) : Grid { val data = rows.flatMap { it.map(fn) } return ListGrid(width, height, data) } + + override fun set(x: Int, y: Int, value: Char) { + rows[y] = rows[y].replaceRange(x, x + 1, value.toString()) + } } diff --git a/2024/src/main/kotlin/Grid.kt b/2024/src/main/kotlin/Grid.kt index fa72d3b..d668d76 100644 --- a/2024/src/main/kotlin/Grid.kt +++ b/2024/src/main/kotlin/Grid.kt @@ -4,22 +4,29 @@ interface Grid { fun map(fn: (T) -> U): Grid - fun get(x: Int, y: Int): T + operator fun get(x: Int, y: Int): T + operator fun set(x: Int, y: Int, value: T) data class Coordinate(val x: Int, val y: Int) fun inside(coordinate: Coordinate) = coordinate.x in 0.. Grid.set(coordinate: Grid.Coordinate, value: T) = set(coordinate.x, coordinate.y, value) operator fun Grid.get(coordinate: Grid.Coordinate) = get(coordinate.x, coordinate.y) operator fun Grid.contains(coordinate: Grid.Coordinate) = inside(coordinate) -class ListGrid(override val width: Int, override val height: Int, private val content: List) : Grid { +class ListGrid(override val width: Int, override val height: Int, content: List) : Grid { init { assert(width * height == content.count()) } - override fun get(x: Int, y: Int): T = content[x + y * width] + private val content = content.toMutableList() - override fun map(fn: (T) -> U): Grid = ListGrid(width, height, content.map(fn)) + override fun get(x: Int, y: Int): T = content[x + y * width] + override fun set(x: Int, y: Int, value: T) { + content[x + y * width] = value + } + + override fun map(fn: (T) -> U): Grid = ListGrid(width, height, content.map(fn).toMutableList()) }