Minor improvements to the solver

This commit is contained in:
Christian Basler
2024-07-11 18:03:13 +02:00
parent 82a5660bc9
commit 7ad0b69933
2 changed files with 13 additions and 8 deletions

View File

@@ -19,6 +19,14 @@ class Grid(
return this[item.itemType.companion].first { it.selection == item } return this[item.itemType.companion].first { it.selection == item }
} }
fun anyCell(predicate: (GameCell<ItemClass<*>>) -> Boolean): Boolean {
return flatMap { it }.any(predicate)
}
fun allCells(predicate: (GameCell<ItemClass<*>>) -> Boolean): Boolean {
return flatMap { it }.all(predicate)
}
override fun toString(): String { override fun toString(): String {
return joinToString("\n") { row -> return joinToString("\n") { row ->
row.joinToString("") { it.selection?.symbol ?: " " } row.joinToString("") { it.selection?.symbol ?: " " }

View File

@@ -1,8 +1,6 @@
package ch.dissem.yaep.domain package ch.dissem.yaep.domain
import ch.dissem.yaep.domain.PuzzleSolution.MULTIPLE_SOLUTIONS import ch.dissem.yaep.domain.PuzzleSolution.*
import ch.dissem.yaep.domain.PuzzleSolution.NO_SOLUTION
import ch.dissem.yaep.domain.PuzzleSolution.SOLVABLE
import kotlin.random.Random import kotlin.random.Random
fun generateGame(size: Int = 6): Game { fun generateGame(size: Int = 6): Game {
@@ -64,12 +62,10 @@ internal fun solve(
} while (removedOptions) } while (removedOptions)
// If any cell has no items left, the puzzle has no solution. // If any cell has no items left, the puzzle has no solution.
if (grid.flatMap { it }.any { cell -> cell.options.isEmpty() }) { if (grid.anyCell { cell -> cell.options.isEmpty() }) return NO_SOLUTION
return NO_SOLUTION
}
// If all cells have exactly one item left, the puzzle is solved. // If all cells have exactly one item left, the puzzle is solved.
if (grid.flatMap { it }.all { it.selection != null }) return SOLVABLE if (grid.allCells { it.selection != null }) return SOLVABLE
// If there are still cells with multiple items, pick one and try each item in turn, then go back to step 2. // If there are still cells with multiple items, pick one and try each item in turn, then go back to step 2.
for (i in 0 until grid.size) { for (i in 0 until grid.size) {
@@ -88,6 +84,7 @@ internal fun solve(
} }
} }
} }
// This shouldn't happen, as we don't check if there are more solutions once we find one
return MULTIPLE_SOLUTIONS return MULTIPLE_SOLUTIONS
} }
@@ -180,4 +177,4 @@ fun getAllClues(rows: List<List<Item<ItemClass<*>>>>): MutableSet<Clue> {
} }
} }
return clues return clues
} }