Minor improvements to the solver
This commit is contained in:
@@ -19,6 +19,14 @@ class Grid(
|
||||
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 {
|
||||
return joinToString("\n") { row ->
|
||||
row.joinToString("") { it.selection?.symbol ?: " " }
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package ch.dissem.yaep.domain
|
||||
|
||||
import ch.dissem.yaep.domain.PuzzleSolution.MULTIPLE_SOLUTIONS
|
||||
import ch.dissem.yaep.domain.PuzzleSolution.NO_SOLUTION
|
||||
import ch.dissem.yaep.domain.PuzzleSolution.SOLVABLE
|
||||
import ch.dissem.yaep.domain.PuzzleSolution.*
|
||||
import kotlin.random.Random
|
||||
|
||||
fun generateGame(size: Int = 6): Game {
|
||||
@@ -64,12 +62,10 @@ internal fun solve(
|
||||
} while (removedOptions)
|
||||
|
||||
// If any cell has no items left, the puzzle has no solution.
|
||||
if (grid.flatMap { it }.any { cell -> cell.options.isEmpty() }) {
|
||||
return NO_SOLUTION
|
||||
}
|
||||
if (grid.anyCell { 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
|
||||
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.
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user