I have to make a sudoku template, so I need to get random numbers into the matrix, but they can not be repeated in the rows or columns, but I can not do it. For this I can not use numpy. In this case I did in the code below but it does not work:
import random
matrix = []
for i in range(9):line = []for j in range(9):number = random.randint(1, 9)if number != i and number != j:line.append(number)matrix.append(line)for i in range(9):print(matrix[i])
A sudoku board has very little chance of being valid with random numbers. You will need a topological sort (dynamic programming) to satisfy the row, column and block constraints.
For example:
known = [ [0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0],[0,0,0, 0,0,0, 0,0,0]]import random
groups = [ p//27*3+p%9//3 for p in range(81) ]
colNums = [ set(range(1,10)) for _ in range(9) ]
rowNums = [ set(range(1,10)) for _ in range(9) ]
grpNums = [ set(range(1,10)) for _ in range(9) ]
sudoku = [ [0]*9 for _ in range(9) ]
for pos in range(81):row,col,group = pos//9,pos%9,groups[pos]fixed = known[row][col]if fixed:sudoku[row][col] = fixedcolNums[col].discard(fixed)rowNums[row].discard(fixed)grpNums[group].discard(fixed)pos = 0
tried = [ set() for _ in range(81)]
while pos in range(81):row,col,group = pos//9,pos%9,groups[pos]number = sudoku[row][col]fixed = known[row][col]if number != 0 and not fixed:sudoku[row][col] = 0colNums[col].add(number)rowNums[row].add(number)grpNums[group].add(number)available = {fixed} if fixed else colNums[col] & rowNums[row] & grpNums[group]available -= tried[pos]if available:number = fixed or random.choice(list(available))if not fixed:sudoku[row][col] = numbercolNums[col].discard(number)rowNums[row].discard(number)grpNums[group].discard(number)tried[pos].add(number)pos += 1else:tried[pos] = set()pos -= 1if pos < 81:print("FAILED!")
else :for r,line in enumerate(sudoku):print(*[line[i:][:3] for i in range(0,9,3)],"\n"*(r%3==2))
This algorithm attempts to fill the each position using the remaining numbers that are not already used on the same row, column or group (block). The colNums
,rowNums
and grpNums
variables keep track of the remaining available numbers in each column, row and group. When a position cannot be filled, the algorithm backtracks to the previous position and tries another number that has not yet been tried for that position.
The known
matrix can be initialized with fixed values that will be forced at their respective position in the resulting sudoku matrix. It can be used to solve sudoku problems or to validate that a problem is doable.