Make grid mutable.
This commit is contained in:
parent
03ddb2a0e6
commit
3351c1f4a7
2 changed files with 20 additions and 5 deletions
|
@ -1,7 +1,11 @@
|
|||
class CharGrid(val rows: List<String>) : Grid<Char> {
|
||||
class CharGrid(rows: List<String>) : Grid<Char> {
|
||||
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<String>) : Grid<Char> {
|
|||
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())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,22 +4,29 @@ interface Grid<T> {
|
|||
|
||||
fun <U> map(fn: (T) -> U): Grid<U>
|
||||
|
||||
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..<width && coordinate.y in 0..<height
|
||||
}
|
||||
|
||||
operator fun <T> Grid<T>.set(coordinate: Grid.Coordinate, value: T) = set(coordinate.x, coordinate.y, value)
|
||||
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)
|
||||
|
||||
class ListGrid<T>(override val width: Int, override val height: Int, private val content: List<T>) : Grid<T> {
|
||||
class ListGrid<T>(override val width: Int, override val height: Int, content: List<T>) : Grid<T> {
|
||||
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 <U> map(fn: (T) -> U): Grid<U> = 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 <U> map(fn: (T) -> U): Grid<U> = ListGrid(width, height, content.map(fn).toMutableList())
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue