Skip to content

Instantly share code, notes, and snippets.

@sandeepnmenon
Created August 11, 2021 07:29
Show Gist options
  • Save sandeepnmenon/729c3f02fa157f3b9af3442cde98ede2 to your computer and use it in GitHub Desktop.
Save sandeepnmenon/729c3f02fa157f3b9af3442cde98ede2 to your computer and use it in GitHub Desktop.
Sudoku Sequence Generator
import numpy as np
# Generator for all possible sudoku grids
def sudoku_generator(sudoku):
for y in range(9):
for x in range(9):
# If cell not filled
if sudoku[y][x] == 0:
# Check if any number in the range is valid in the empty cell
for n in range(1,10):
if is_valid(n, y, x, sudoku):
sudoku[y][x] = n
yield from sudoku_generator(sudoku)
# Reset the cell for backtracking
sudoku[y][x] = 0
return
yield sudoku
def is_valid(n, y, x, sudoku):
# Check if number valid in row
for i in range(9):
if sudoku[y][i] == n:
return False
# Check if number valid in column
for j in range(9):
if sudoku[j][x] == n:
return False
# Check if number valid in respective 3x3 tile
for i in range(3):
for j in range(3):
if sudoku[y//3*3+i][x//3*3+j] == n:
return False
return True
if __name__ == '__main__':
# empty sudoku grid
sudoku = np.zeros((9,9), dtype=np.int)
sudoku_seq_generator = sudoku_generator(sudoku)
range_limit = 10
for i in range(range_limit):
print(next(sudoku_seq_generator))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment