|
1 | 1 | package de.ronny_h.extensions |
2 | 2 |
|
3 | | -abstract class Grid<T>(input: List<String>) { |
4 | | - val height = input.size |
5 | | - val width = input[0].length |
| 3 | +import kotlin.collections.MutableList |
| 4 | + |
| 5 | +/** |
| 6 | + * @param nullElement The initial element within the grid |
| 7 | + * @param overrideElement Used for out of bound positions. Defaults to `nullElement` |
| 8 | + */ |
| 9 | +abstract class Grid<T>( |
| 10 | + val height: Int, |
| 11 | + val width: Int, |
| 12 | + protected val nullElement: T, |
| 13 | + private val overrideElement: T = nullElement, |
| 14 | +) { |
| 15 | + |
| 16 | + private val grid: MutableList<MutableList<T>> = MutableList(height) { MutableList(width) { nullElement } } |
6 | 17 |
|
7 | | - abstract val nullElement: T |
8 | 18 | abstract fun Char.toElementType(): T |
9 | 19 |
|
10 | | - private val grid = MutableList(height) { MutableList(width) { nullElement } } |
| 20 | + constructor(height: Int, width: Int, nullElement: T, overrideElement: T = nullElement, overrides: List<Coordinates> = emptyList()) : this(height, width, nullElement, overrideElement) { |
| 21 | + overrides.forEach { |
| 22 | + grid[it.row][it.col] = overrideElement |
| 23 | + } |
| 24 | + } |
11 | 25 |
|
12 | | - init { |
| 26 | + constructor(input: List<String>, nullElement: T, overrideElement: T = nullElement) : this(input.size, input[0].length, nullElement, overrideElement, emptyList()){ |
13 | 27 | input.forEachIndexed { row, line -> |
14 | 28 | line.forEachIndexed { col, char -> grid[row][col] = char.toElementType() } |
15 | 29 | } |
16 | 30 | } |
17 | 31 |
|
18 | 32 | operator fun get(row: Int, col: Int): T { |
19 | | - return grid.getOrNull(row)?.getOrNull(col) ?: nullElement |
| 33 | + return grid |
| 34 | + .getOrNull(row) |
| 35 | + ?.getOrNull(col) |
| 36 | + ?: overrideElement |
20 | 37 | } |
21 | 38 |
|
22 | 39 | fun getAt(position: Coordinates) = get(position.row, position.col) |
|
0 commit comments