I made a program that:
It detects valid and invalid solutions correctly.
I never get errors.
When telling the program to generate a new, random solution, until it finds a valid one, it just keeps running.
The way I generate the attempted 'solutions' is by making a list of 9 lists of 9 numbers each, each list being the numbers 1-9 mixed up, like so:
SUDOKU_ATTEMPT = [[8, 9, 6, 3, 7, 4, 2, 5, 1],
[6, 3, 4, 8, 1, 9, 7, 2, 5],
[1, 2, 5, 6, 8, 4, 7, 3, 9],
[1, 2, 9, 4, 3, 7, 8, 5, 6],
[6, 4, 9, 2, 3, 1, 7, 8, 5],
[3, 1, 8, 2, 7, 4, 9, 5, 6],
[3, 7, 2, 8, 4, 9, 5, 6, 1],
[7, 2, 1, 6, 4, 5, 3, 8, 9],
[2, 7, 8, 9, 4, 5, 1, 3, 6]]
As you can see, rows
will be correct.
But not (necessarily) columns
, nor 3 x 3 boxes
.
Posts I checked:
- Random sudoku generation (but it's C - not python).
- Recursive solution to Sudoku generator (Java - not python).
- Generating minimal/irreducible Sudokus (bumped into it, but not my question).
- Java sudoku generator not working correctly (Java. Also, it's a different problem).
- Generation of sudoku questions (different question).
- Sudoku generator loop (Java, different question).
- Sudoku generation speed (Java)
- Sudoku Generator (Different question).
Please consider up voting. If you think this question can be improved, please suggest how.
For the record, and from the discussion in comments:
You are basically generating random 9x9 matrices until one is a sudoku solution. The problem is that you use very weak constraints: integers from 1 to 9, and unique on each row.
The probability that you actually generate a valid solution is very low (it's a good math exercise to compute it!). Therefore, your code is likely to run seemingly forever, even though it logically terminates.
Relying on the randomness to this extent is not the right solution in this case.