scalarecursionknights-tourimmutable-collections

Recursion in scala wont stop


I have a method which helps me to solve a knight's tour. I want my recursion to stop as soon as I have found a solution however It keeps going on and on.

At the end it returns nearly 20 different solutions. I have added my code below, Can Someone please point out what is wrong here?

def myRecursion(dimension: Int, solution: Solution) : Option[Solution] = {

    if ( dimension * dimension == solution.size) {
        println("Stop it now")
        Some(solution)
    } else {
        val movesAvailable = possibleMoves(dimension, solution, solution.head) 
        val bestm = bestMoves(movesAvailable)

        if ( bestm.isDefined ) {
            myRecursion(dimension, bestm.get ::: solution)
        } else {
            movesAvailable.foreach{ x => 
                if(myRecursion(dimension, x:: solution).isDefined){
                    x::solution;
                } 
            }
            None

        }
    }
}

Solution

  • movesAvailable.foreach{ x => 
                    if(myRecursion(dimension, x:: solution).isDefined){
                        x::solution;
                    } 
                }
    None
    

    Thats probably your issue. You're calling your function recursively in a loop, but you don't actually exit the loop if its successful. You could probably switch that around to a takeWhile that keeps going while myRecursions returns None.

    Also, that chunk of code isn't doing anything right now - You've got an if statement that evaluates to something, but then you return None no matter what.