Add tests

This commit is contained in:
Christian Basler
2024-06-24 18:42:39 +02:00
parent f76be158a0
commit 4c7cc68024
5 changed files with 66 additions and 33 deletions

View File

@@ -18,10 +18,6 @@ fun generateGame(size: Int = 6): Game {
// if there are 5 houses, there are 5 possible clues of the form "Person A lives in
// house B", 8 possible clues of the form "Person A lives next to house B", and so on.)
var clues = getAllClues(grid).shuffled()
// var positionClues: MutableSet<PositionClue<out ItemClass<*>>> = grid.flatMap { row ->
// row.mapIndexed { i, item -> PositionClue(item, i) }
// }.toMutableSet()
var i = 0
@@ -51,13 +47,14 @@ private fun solve(
// First, set the positions of the items that are already known.
clues.filterIsInstance<PositionClue<ItemClass<*>>>().forEach { position ->
val row = grid[position.item.itemType.companion]
val newSelections = mutableListOf<GameCell<ItemClass<*>>>()
row.forEachIndexed { index, gameCell ->
if (index == position.index) {
gameCell.selection = position.item
} else {
gameCell.options.remove(position.item)
newSelections.add(gameCell)
}
}
newSelections.forEach { row.cleanupOptions(it) }
}
// For each clue, remove any items that violate the clue.
@@ -73,11 +70,10 @@ private fun solve(
} while (removedOptions)
// If any cell has no items left, the puzzle has no solution.
grid.flatMap { it }.forEach { cell ->
if (cell.options.isEmpty()) {
return NO_SOLUTION
}
if (grid.flatMap { it }.any { cell -> cell.options.isEmpty() }) {
return NO_SOLUTION
}
// If all cells have exactly one item left, the puzzle is solved.
if (grid.flatMap { it }.all { it.selection != null }) return SOLVABLE
@@ -122,11 +118,11 @@ fun <C : ItemClass<C>> GameRow<C>.cleanupOptions(cell: GameCell<C>) {
private fun getAllClues(rows: List<List<Item<ItemClass<*>>>>): MutableSet<Clue> {
val clues = mutableSetOf<Clue>()
rows.forEach { row ->
row.forEachIndexed { i, item ->
clues.add(PositionClue(item, i))
}
}
// rows.forEach { row ->
// row.forEachIndexed { i, item ->
// clues.add(PositionClue(item, i))
// }
// }
rows.forEach { columns ->
columns.forEachIndexed { j, item ->