https://kotlinlang.org logo
Title
a

ar-g

05/05/2020, 4:55 PM
Hi everyone, I have a code with a mix of recursion and coroutines, I'm wondering how valid and idiomatic it is: • each step when the board is changed I want to emit it with
flow
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
    }
z

zak.taccardi

05/05/2020, 5:03 PM
with code this big, should attach as a code snippet
u

uli

05/06/2020, 10:37 PM
Could not read it either. But where does
partiallySolve
suspend?