How To Create a Solved Sudoku
Articles —> How To Create a Solved Sudoku
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.
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
4 | 5 | 6 | 7 | 8 | 9 | 1 | 2 | 3 |
7 | 8 | 9 | 1 | 2 | 3 | 4 | 5 | 6 |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 1 |
5 | 6 | 7 | 8 | 9 | 1 | 2 | 3 | 4 |
8 | 9 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 1 | 2 |
6 | 7 | 8 | 9 | 1 | 2 | 3 | 4 | 5 |
9 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
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
• | ↔ | • | ||||||
3 | 2 | 1 | 4 | 5 | 6 | 7 | 8 | 9 |
6 | 5 | 4 | 7 | 8 | 9 | 1 | 2 | 3 |
9 | 8 | 7 | 1 | 2 | 3 | 4 | 5 | 6 |
4 | 3 | 2 | 5 | 6 | 7 | 8 | 9 | 1 |
7 | 6 | 5 | 8 | 9 | 1 | 2 | 3 | 4 |
1 | 9 | 8 | 2 | 3 | 4 | 5 | 6 | 7 |
5 | 4 | 3 | 6 | 7 | 8 | 9 | 1 | 2 |
8 | 7 | 6 | 9 | 1 | 2 | 3 | 4 | 5 |
2 | 1 | 9 | 3 | 4 | 5 | 6 | 7 | 8 |
Now shift by rows:
• | 9 | 8 | 7 | 1 | 2 | 3 | 4 | 5 | 6 |
↓ | 6 | 5 | 4 | 7 | 8 | 9 | 1 | 2 | 3 |
• | 3 | 2 | 1 | 4 | 5 | 6 | 7 | 8 | 9 |
4 | 3 | 2 | 5 | 6 | 7 | 8 | 9 | 1 | |
7 | 6 | 5 | 8 | 9 | 1 | 2 | 3 | 4 | |
1 | 9 | 8 | 2 | 3 | 4 | 5 | 6 | 7 | |
5 | 4 | 3 | 6 | 7 | 8 | 9 | 1 | 2 | |
8 | 7 | 6 | 9 | 1 | 2 | 3 | 4 | 5 | |
2 | 1 | 9 | 3 | 4 | 5 | 6 | 7 | 8 |
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).
- Mattias l - December, 1, 2018
I also figured out this algorithm. I found this post when googling the problem with it. When doing it like this the numbers 123 will always be on the same row in every cell, and there is other patterns for the rows.