Search code examples
algorithmf#immutabilitymutablebacktracking

Backtracking Algorithm in F#: How does immutability work?


Ok, so I am trying to write a backtracking algorithm that can take input like:

0 2 3 1 (top-right location, length, horizontal or vertical)
1 0 4 0
2 2 4 0
1 3 3 1
top (the actual words)
that
toga
cat

And spit out a crossword, like:

**c***
that**
**toga
***p**

The code I have thus far is:

//prints the puzzle
let printPuzzle (puzzle : char[,]) =
    printfn "%s" ""
    printfn "%A" puzzle
    printfn "%s" ""

//checks if the words fits
let rec doesItFit place (puzzle : char[,]) (word : seq<char>) =
    let (row, col, length, isVertical) = place
    if length <> (Seq.length word) then
        (puzzle, false)
    else
        match (Seq.toList word) with
        | [] -> (puzzle, true)
        | letter::rest ->
            printfn "%c" letter
            printPuzzle puzzle
            if isVertical = 0 then
                if puzzle.[row, col] = '*' || puzzle.[row, col] = letter then
                    puzzle.[row, col] <- letter
                    doesItFit (row, col+1, length-1, isVertical) puzzle rest 
                else
                    (puzzle, false)
            else
                if puzzle.[row, col] = '*' || puzzle.[row, col] = letter then
                    puzzle.[row, col] <- letter
                    doesItFit (row+1, col, length-1, isVertical) puzzle rest   
                else
                    (puzzle, false)

//the actual backtracking algorithm... goes through all places and all words
//trying to make stuff fit
let rec sort words places (puzzle : char[,]) =
    match places with
    | [] -> (puzzle, true)
    | place::rest ->
        let rec checkWords words place puzzle =
            match words with
            | [] ->
                printfn "%s" "failure, backtracking" 
                puzzle, false
            | word::otherWords ->
                let attempt = doesItFit place puzzle word
                if snd attempt then
                    printfn "%s" "success, entering if block"
                    let nextLevel = sort words rest (fst attempt)
                    if (snd nextLevel) then
                        nextLevel
                    else
                        checkWords otherWords place puzzle
                else
                    checkWords otherWords place puzzle
        checkWords words place puzzle

//line for testing
printPuzzle (fst (sort ["cat"; "that"; "toga"; "top"] [(0, 2, 3, 1); (1, 0, 4, 0); (2, 2, 4, 0); (1, 3, 3, 1)] (Array2D.create 6 6 '*')));;

Here is the output from running the test line:

c

[['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

a

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['*'; '*'; 'a'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

success, entering if block
t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['*'; '*'; 'a'; '*'; '*'; '*']
 ['*'; '*'; 't'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

h

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; '*'; 'a'; '*'; '*'; '*']
 ['*'; '*'; 't'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

a

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; '*'; '*'; '*']
 ['*'; '*'; 't'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; '*'; '*'; '*']
 ['*'; '*'; 't'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

success, entering if block
t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

h

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

a

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

success, entering if block
t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

o

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

failure, backtracking
t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

o

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

failure, backtracking
t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

o

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

failure, backtracking
t

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

failure, backtracking

[['*'; '*'; 'c'; '*'; '*'; '*']
 ['t'; 'h'; 'a'; 't'; '*'; '*']
 ['*'; '*'; 't'; 'h'; 'a'; 't']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']
 ['*'; '*'; '*'; '*'; '*'; '*']]

I think my problem is that I'm not sure how immutability works in F#. It seems from what my program does that when the puzzle is passed in after a failed attempt, the puzzle has been modified. That does not make much sense to me, as I thought F# would not let it be modified. What I would like is an explanation of why this code uses the modified puzzle when testing a word after backtracking out, rather than the original, unmodified puzzle.


Solution

  • Your code uses mutable array char[,] to represent puzzle, so when you mutate it in the doesItFit function (using the <- operator), you are actually changing the state of the object. When the code returns from the doesItFit function, the array has changed.

    There are essentially three ways to solve the problem:

    • Use immutable types to represent puzzles - if you use F# list (list of lists) to represent puzzles, then you cannot mutate it (because lists are immutable) and so you don't get into this situation

    • Clone objects as needed - you don't have to use immutable types to write code in a functional style. Just clone the array before you pass it to a function that may mutate it. You can use Array.copy for that.

    • Restore the state before backtracking - when the function fails, it should undo all modifications
      (This is not a purely functional approach, but it might be more efficient - think of it as optimization)