diff --git a/domain/src/main/kotlin/ch/dissem/yaep/domain/Grid.kt b/domain/src/main/kotlin/ch/dissem/yaep/domain/Grid.kt index 04f7510..1406973 100644 --- a/domain/src/main/kotlin/ch/dissem/yaep/domain/Grid.kt +++ b/domain/src/main/kotlin/ch/dissem/yaep/domain/Grid.kt @@ -19,6 +19,14 @@ class Grid( return this[item.itemType.companion].first { it.selection == item } } + fun anyCell(predicate: (GameCell>) -> Boolean): Boolean { + return flatMap { it }.any(predicate) + } + + fun allCells(predicate: (GameCell>) -> Boolean): Boolean { + return flatMap { it }.all(predicate) + } + override fun toString(): String { return joinToString("\n") { row -> row.joinToString("") { it.selection?.symbol ?: " " } diff --git a/domain/src/main/kotlin/ch/dissem/yaep/domain/generator.kt b/domain/src/main/kotlin/ch/dissem/yaep/domain/generator.kt index ba7246d..d7f7a84 100644 --- a/domain/src/main/kotlin/ch/dissem/yaep/domain/generator.kt +++ b/domain/src/main/kotlin/ch/dissem/yaep/domain/generator.kt @@ -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 } @@ -180,4 +177,4 @@ fun getAllClues(rows: List>>>): MutableSet { } } return clues -} \ No newline at end of file +}