Skip to content

Instantly share code, notes, and snippets.

@dkandalov
Created November 18, 2017 15:50
Show Gist options
  • Select an option

  • Save dkandalov/26994da8d2490158a58a52e3d3c483f3 to your computer and use it in GitHub Desktop.

Select an option

Save dkandalov/26994da8d2490158a58a52e3d3c483f3 to your computer and use it in GitHub Desktop.
package katas.kotlin.aaa
import katas.kotlin.shouldEqual
import org.junit.Test
data class Cell(val x: Int, val y: Int)
data class Board(val cells: List<Cell> = emptyList()) {
fun evolve(): Board {
val newCells = cells.mapNotNull { cell ->
val n = neighbours(cell).size
if (n == 3 || n == 4) cell else null
}
val deadNeighbours = cells
.flatMap { cell -> neighbours(cell) }
.distinct()
.filterNot { cells.contains(it) }
deadNeighbours.mapNotNull { cell ->
}
return Board(newCells)
}
private fun neighbours(cell: Cell): List<Cell> {
val shifts = listOf(
Pair(0, -2),
Pair(0, 2),
Pair(-1, -1),
Pair(-1, 1),
Pair(1, -1),
Pair(1, 1)
)
return shifts
.map { shift -> Cell(cell.x + shift.first, cell.y + shift.second) }
.filter { cells.contains(it) }
}
}
class HexagonalGameOfLIfe {
@Test fun `empty board evolves to an empty board`() {
Board().evolve() shouldEqual Board()
}
@Test fun `single cell evolves to an empty board`() {
Board(cells = listOf(Cell(0, 0))).evolve() shouldEqual Board()
}
@Test fun `two cells evolves to an empty board`() {
Board(cells = listOf(Cell(0, 0), Cell(0, 2))).evolve() shouldEqual Board()
}
@Test fun `cell with 2 neighbours evolve to an empty board`() {
Board(cells = listOf(Cell(0, -2), Cell(0, 0), Cell(0, 2))).evolve() shouldEqual Board()
}
@Test fun `cell with 3 or 4 neighbours stays alive`() {
Board(cells = listOf(
Cell(0, -2),
Cell(0, 0),
Cell(1, -1),
Cell(1, 1)
)).evolve() shouldEqual Board(cells = listOf(
Cell(0, 0),
Cell(1, -1)
))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment