Next iteration of my code changes ...
Now each board step shows:
- the peg target
- the position jumped over
- the position left
The calculation of the complete solution is also encapsulated into a self-contained function. No globals.
This is a necessary step before I move this into a separate module, in order to be able to code a graphical representation more conveniently.
It looks like this:
solve = function()
// Possible moves
pm = [-11, -9, 2, 11, 9, -2]
solveStep = function(board, left, steps)
// Push board for the time being
// If it leads to a solution it will remain
// Otherwise it will be removed at the end
steps.push board
// End recursion when solved
if left == 1 then
return true
end if
// Normalize board before calculating
board = board.replace("X","x")
board = board.replace(",",".")
board = board.replace("-",".")
// Otherwise try solutions
for i in range( 0, len(board)-1 ) // to boardsize
if board[i] == "x" then // peg found
for j in range( 0, len(pm)-1 ) // to all moves
// for better readability:
mj = pm[j] ; over = i+mj ; tgt = i+2*mj
if ( tgt >= 1 and
tgt <= len(start)-1 and
board[tgt] == "." and
board[over] == "x" ) then
// Move: set special chars for involved positions
board=board[:i] + "," + board[i+1:]
board=board[:over] + "-" + board[over+1:]
board=board[:tgt] + "X" + board[tgt+1:]
// >RECURSION<
solved = solveStep(board,left-1,steps)
if solved then
return true
end if
// Unmove:
board=board[:i]+"x"+board[i+1:] // "x"
board=board[:over]+"x"+board[over+1:] // "x"
board=board[:tgt]+"."+board[tgt+1:] // "."
end if
end for
end if
end for
// We run into a dead-alley, remove board from steps
steps.pop
return false
end function
// NOTE: board must have a blank line at the top and bottom.
// Starting state:
startLines = [
" ",
" . ",
" x x ",
" x x x ",
" x x x x ",
"x x x x x",
" "]
start = startLines.join(char(13))
solutionSteps = []
solveStep(start, 14, solutionSteps)
return solutionSteps
end function
pause = function()
print "Press a key ..."
key.get
end function
main = function()
solutionSteps = solve
for step in solutionSteps
clear
pprint step
if step != solutionSteps[-1] then pause
end for
print "Solved!"
end function
main
```ms