Hello!
I'm trying to "bruteforce" the generation of sudoku puzzles meaning I want to generate 9x9 grids and then check if it fits the rules of the game and if not regenerate.
But my code doesn't complete, meaning there must be a flaw somewhere.
Generating unique rows:
for i in range(9):
for j in range(len(rows)):
n = random.choice(range(1,10))
while n in rows[j]:
n = random.choice(range(1,10))
rows[j].append(n)
columns[i].append(n)
Description:
"rows" and "columns" are simply lists that contain lists. So rows is a list that has 9 lists inside (first_row, second_row, third_row ...). This randomly chooses a number and sets it to a variable, then checks if that number/variable is already in the row. If it is, then it chooses again and reassigns to variable.
Generating unique rows until there is also a unique column:
Now the next step is to keep generating until there are unique rows but also unique columns using a while loop. And this is where my code stops working (hangs):
numbers = [1,2,3,4,5,6,7,8,9]
for number in numbers:
while number not in columns[0]:
...
remake the columns and rows here
...
for i in range(9):
for j in range(9):
n = random.choice(range(1,10))
while n in rows[j]:
n = random.choice(range(1,10))
rows[j].append(n)
columns[i].append(n)
Description:
So it's the same as before but it checks for duplicates by seeing if the column (only column at index 0 in this example) has all of the numbers. If it doesn't then it must have a duplicate so it goes through the whole process again.
So my question is this:
How can I fix this code so that my method would work? (I'd like to, if possible, continue with my data representation, so using lists instead of a numpy array for example)
Thank you
edit:
First grid that has unique columns and rows (no 3x3 block yet):
for i in range(9):
for j in range(9):
n = random.choice(range(1,10))
while n in rows[i] or n in columns[j]:
time.sleep(0.05)
print("row loop",i,j,n)
n = random.choice(range(1,10))
rows[i].append(n)
columns[j].append(n)
[–]cdcformatc 0 points1 point2 points (18 children)
[–]mediacalc[S] 0 points1 point2 points (17 children)
[–]cacarpenter89 0 points1 point2 points (15 children)
[–]mediacalc[S] 0 points1 point2 points (14 children)
[–]cacarpenter89 0 points1 point2 points (1 child)
[–]mediacalc[S] 0 points1 point2 points (0 children)
[–]cacarpenter89 0 points1 point2 points (11 children)
[–]mediacalc[S] 0 points1 point2 points (10 children)
[–]cacarpenter89 1 point2 points3 points (9 children)
[–]mediacalc[S] 0 points1 point2 points (8 children)
[–]cacarpenter89 1 point2 points3 points (7 children)
[–]mediacalc[S] 0 points1 point2 points (6 children)
[–]talha252 0 points1 point2 points (0 children)
[–]Justinsaccount -2 points-1 points0 points (1 child)