How To Create a Solved Sudoku

Articles —> How To Create a Solved Sudoku

Sudoku game board

When I first started playing with writing a sudoku game, I took the long way to create sudoku templates. Using a recursive algorithm, I would slowly fill up the grid with random numbers - checking the validity of the puzzle at each step. If I hit a roadblock where the puzzle cannot be completed, the algorithm would backtrack until it could move forward, and then move forward again. Brute force to say the least.

There is a more elegant solution however: create a solved sudoku and then shuffle it.

Step 1: Creating the solved sudoku is easy: just shift the row above to the left by 3 unless its vertical index is equally divisible by 3 (starting with index 0) in which case shift the row above by 4.

123456789
456789123
789123456
234567891
567891234
891234567
345678912
678912345
912345678

Step 2: Shuffle the rows and columns. Of course, to do so and ensure the sudoku rules maintain integrity, you can only shuffle rows and columns of the same group: groups being 1-3, 4-6, and 7-9. Demonstrated below, the columns 1 and 3 are shuffled

321456789
654789123
987123456
432567891
765891234
198234567
543678912
876912345
219345678

Now shift by rows:

987123456
654789123
321456789
432567891
765891234
198234567
543678912
876912345
219345678

And this can be continued for as many iterations as one likes, shuffling random rows and columns from a random group, resulting in a pseudo-random puzzle. I am still waiting for the day when I solve a puzzle and the result is the first puzzle above: not sure I would even notice until it is close to being solved.



Comments

  • Para Parasolian   -   October, 2, 2016

    OK, I see a solved puzzle. Now how do you erase some of the cells to create the puzzle? (and ensure that the result is unique, and that you have erased all possible cells).

Back to Articles


© 2008-2017 Greg Cope