Skip to content

Instantly share code, notes, and snippets.

@joelburton
Last active September 20, 2021 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/2abb13eebc7b37975179488c99a21890 to your computer and use it in GitHub Desktop.
Save joelburton/2abb13eebc7b37975179488c99a21890 to your computer and use it in GitHub Desktop.
Leveret Lunch in Functional Kotlin
data class Cell(val y: Int, val x: Int) {
fun neighbors() = listOf(Cell(y, x - 1), Cell(y - 1, x), Cell(y, x + 1), Cell(y + 1, x)) // WNES
}
data class Garden(val cells: List<List<Int>>) {
val nRows = cells.size
val nCols = cells[0].size
fun findCenterCells() = listOf(
Cell((nRows - 1) / 2, (nCols - 1) / 2), // NW
Cell((nRows - 1) / 2, (nCols - 0) / 2), // NE
Cell((nRows - 0) / 2, (nCols - 1) / 2), // SW
Cell((nRows - 0) / 2, (nCols - 0) / 2), // SE
)
fun nextCell(coords: List<Cell>, carrots: Int = 0, seen: Set<Cell> = setOf()): Int =
coords
.filter { it.y in 0 until nRows && it.x in 0 until nCols }
.filter { it !in seen }
.maxByOrNull { cells[it.y][it.x] } // cell with max # of carrots, preferring first
.let {
if (it == null || cells[it.y][it.x] == 0) carrots
else nextCell(it.neighbors(), carrots + cells[it.y][it.x], seen + it)
}
}
with(
Garden(
listOf(
listOf(9, 9, 9, 9),
listOf(9, 3, 1, 0),
listOf(9, 1, 4, 2),
listOf(9, 9, 1, 0),
)
)
) { nextCell(findCenterCells()) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment