Improve solver (WIP, currently broken)

This commit is contained in:
2024-07-14 07:47:35 +02:00
parent fbf6e466c7
commit ca22fb9f2f

View File

@@ -1,6 +1,8 @@
package ch.dissem.yaep.domain package ch.dissem.yaep.domain
import ch.dissem.yaep.domain.PuzzleSolution.* import ch.dissem.yaep.domain.PuzzleSolution.MULTIPLE_SOLUTIONS
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 {
@@ -68,24 +70,33 @@ internal fun solve(
if (grid.cells.all { it.selection != null }) return SOLVABLE if (grid.cells.all { 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) { return if (
for (j in 0 until grid.size) { grid.cells
val cell = grid[i][j] .filter { it.selection == null }
if (cell.selection == null) { .any { it.countSolutions(grid, clues) == 1 }
val options = cell.options.toList() ) {
for (option in options) { SOLVABLE
cell.selection = option } else {
if (solve(grid, clues) == SOLVABLE) { MULTIPLE_SOLUTIONS
return SOLVABLE }
} }
}
cell.selection = null internal fun <C : ItemClass<C>> GameCell<C>.countSolutions(
cell.options.addAll(options) grid: Grid,
} clues: Collection<Clue>
): Int {
val options = options.toList()
var solvableCount = 0
for (option in options) {
selection = option
if (solve(grid, clues) == SOLVABLE) {
solvableCount++
} }
} }
// This shouldn't happen, as we don't check if there are more solutions once we find one selection = null
return MULTIPLE_SOLUTIONS this.options.addAll(options)
return solvableCount
} }
internal enum class PuzzleSolution { internal enum class PuzzleSolution {