Solving according to strategies is pretty straightforward. Generating puzzles is more complex and exercises your comfort with recursion. In general terms generating a puzzle follows these steps
- Create an empty grid
- Use brute force to solve
- Remove random ‘sures’ to reach a target number of givens, ensuring that the result is solvable using the level of difficulty strategies you are aiming for.
while grid Solvable and not Solved for each random cell not Solved make a random possibility into a sure recurs
Private Sub Brute() Dim ic As Long, indexOfCell As Long, ip As Long, iCollectionIndex As Long, iz As Long, indexInList As Long, idx As Long Dim sc As cSudCell 'this one solves by brute force, and would be used for generating ' first find the next unsure cell Set sc = pGrid.nextrandomUnSure Debug.Assert Not sc Is Nothing indexOfCell = sc.Index ' this instance of brute will deal solely with this cell, and recurse for the next one ' try every possibilty in a random order for this cell till one sticks ip = pGrid.Item(indexOfCell).nextRandomPossibility While ip <> 0 ' clone a new grid for this particular route iCollectionIndex = pGrid.CollectionIndex newGrid pGrid With pGrid .Item(indexOfCell).makeSure ip .solve If .isSolved Then GoTo wrapup ' if still solvable then guess for the next cell along If Not .isScrewedUp Then Brute ' the puzzle is solved...? If isSolved Then GoTo wrapup ' if we get here then we have used a non viable guess, so backtrack by scrapping the current grid pCollection.Remove (.CollectionIndex) End With ' go back to the grid before we tried that abortive possibility and try another Set pGrid = pCollection(iCollectionIndex) ip = pGrid.Item(indexOfCell).nextRandomPossibility Wend wrapup: ' should only get here if all is solved Debug.Assert isSolved End Sub