Search code examples
pythonpython-2.7randomsudoku

Sudoku Checker & Generator: Checks But Won't Generate


I made a program that:

  1. Generates (possibly wrong) sudoku solutions.
  2. Checks if a solution is correct
  3. If it is, prints it.
  4. If not, back to step 1.

It detects valid and invalid solutions correctly.
I never get errors.

But:

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:

Please consider up voting. If you think this question can be improved, please suggest how.


Solution

  • 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.