ar-g
05/05/2020, 4:55 PMflow
and show on UI
• when the coroutine
is canceled partiallySolve
function expected to stop working
typealias OnSudokuBoardChanged = suspend (board: List<List<Int>>) -> Unit
class SudokuSolver {
fun solve(board: List<List<Int>>) = flow {
partiallySolve(0, 0, board) {
emit(it)
}
}
private suspend fun partiallySolve(
curI: Int,
curJ: Int,
board: MutableList<MutableList<Int>>,
callback: OnSudokuBoardChanged
): Boolean {
if (curI > board.lastIndex) {
return true
}
val curNum = board[curI][curJ]
val nextI = if (curJ == board.lastIndex) curI + 1 else curI
val nextJ = if (curJ == board.lastIndex) 0 else curJ + 1
if (curNum != 0) {
return partiallySolve(nextI, nextJ, board, callback)
}
if (curNum == 0) {
for (guess in 1..9) {
if (validate(guess, curI, curJ, board)) {
board[curI][curJ] = guess
callback.invoke(board)
if (partiallySolve(nextI, nextJ, board, callback)) {
return true
}
}
}
}
board[curI][curJ] = 0
return false
}
zak.taccardi
05/05/2020, 5:03 PMuli
05/06/2020, 10:37 PMpartiallySolve
suspend?