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() ) {
SOLVABLE
} else {
MULTIPLE_SOLUTIONS
}
}
internal fun <C : ItemClass<C>> GameCell<C>.countSolutions(
grid: Grid,
clues: Collection<Clue>
): Int {
val options = options.toList()
var solvableCount = 0
for (option in options) { for (option in options) {
cell.selection = option selection = option
if (solve(grid, clues) == SOLVABLE) { if (solve(grid, clues) == SOLVABLE) {
return SOLVABLE solvableCount++
} }
} }
cell.selection = null selection = null
cell.options.addAll(options) this.options.addAll(options)
}
} return solvableCount
}
// This shouldn't happen, as we don't check if there are more solutions once we find one
return MULTIPLE_SOLUTIONS
} }
internal enum class PuzzleSolution { internal enum class PuzzleSolution {