Skip to content

Instantly share code, notes, and snippets.

@dsteb
Last active October 23, 2021 20:32
Show Gist options
  • Save dsteb/5343b078bcaab223e5c22bc4b7038a10 to your computer and use it in GitHub Desktop.
Save dsteb/5343b078bcaab223e5c22bc4b7038a10 to your computer and use it in GitHub Desktop.
Kotlin for Java Developers: week 4, Programming Assignment: Board
package board
import board.Direction.*
private open class SquareBoardImpl(width: Int) : SquareBoard {
override val width: Int = width
private val cells: List<List<Cell>> = (1..width).map { row ->
(1..width).map { Cell(row, it) }
}
override fun getCellOrNull(i: Int, j: Int): Cell? =
cells.getOrNull(i - 1)?.getOrNull(j - 1)
override fun getCell(i: Int, j: Int): Cell =
cells[i - 1][j - 1]
override fun getAllCells(): Collection<Cell> = cells.flatten()
override fun getRow(i: Int, jRange: IntProgression): List<Cell> =
jRange.mapNotNull { getCellOrNull(i, it) }
override fun getColumn(iRange: IntProgression, j: Int): List<Cell> =
iRange.mapNotNull { getCellOrNull(it, j) }
override fun Cell.getNeighbour(direction: Direction): Cell? =
when(direction) {
UP -> getCellOrNull(i - 1, j)
RIGHT -> getCellOrNull(i, j + 1)
DOWN -> getCellOrNull(i + 1, j)
LEFT -> getCellOrNull(i, j - 1)
}
}
private class GameBoardImpl<T>(width: Int) : SquareBoardImpl(width), GameBoard<T> {
private val values: MutableMap<Cell, T> = mutableMapOf()
override fun get(cell: Cell): T? = values[cell]
override fun set(cell: Cell, value: T?) {
if (value != null) values[cell] = value
}
override fun filter(predicate: (T?) -> Boolean): Collection<Cell> = getAllCells()
.associateWith { values[it] }
.filterValues(predicate)
.keys
override fun find(predicate: (T?) -> Boolean): Cell? = getAllCells()
.map { Pair(it, values[it]) }
.find { (_, value) -> predicate(value) }
?.first
override fun any(predicate: (T?) -> Boolean): Boolean = getAllCells()
.map { Pair(it, values[it]) }
.any { (_, value) -> predicate(value) }
override fun all(predicate: (T?) -> Boolean): Boolean = getAllCells()
.map { Pair(it, values[it]) }
.all { (_, value) -> predicate(value) }
}
fun createSquareBoard(width: Int): SquareBoard = SquareBoardImpl(width)
fun <T> createGameBoard(width: Int): GameBoard<T> = GameBoardImpl(width)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment