Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aking1012/2c9eff41c8fab80bd9c8 to your computer and use it in GitHub Desktop.
Save aking1012/2c9eff41c8fab80bd9c8 to your computer and use it in GitHub Desktop.
Sudoku solver.Working on solving that bottom left three
import numpy
#Build our possibilities matrix
global possibilities, solved
possibilities = numpy.ndarray((9,9,9))
solved = numpy.ndarray((9,9))
i = list(range(9))
j = list(range(9))
for x in i:
for y in j:
possibilities[x][y] = list(range(10))[1:]
#Set our starting game
easy = '017002560034015080009000140450000600020781090008000021096000200080470950045200810'
#Medium
#Hard
#Very Hard
stuck = '000500836058300127103070495501000000006090700000000208972030001000008370800007000'
level = stuck
i=0
for block in level:
if block != '0':
x, y = divmod(i, 9)
possibilities[x][y] = 0
possibilities[x][y][int(block)-1] = int(block)
i+=1
i=0
for block in level:
x, y = divmod(i, 9)
if block != '0':
solved[x][y] = 1
else:
solved[x][y] = 0
i+=1
def iter_square(i, silence=False):
key_blocks = [0,3,6,27,30,33,54,57,60]
x,y = divmod(key_blocks[i], 9)
for j in range(3):
for k in range(3):
if not silence: print(x+j, y+k)
yield(x+j, y+k)
def square_elim():
for i in range(9):
for blockx, blocky in iter_square(i):
if solved[blockx][blocky] == 1:
j=0
for item in possibilities[blockx][blocky]:
if item !=0.:
for blocka, blockb in iter_square(i, silence=True):
if (blocka, blockb) != (blockx, blocky):
possibilities[blocka][blockb][j] = 0.
j+=1
#break
def rows_cols():
for x in range(9):
for y in range(9):
if solved[x][y] == 1:
print('Solved at:')
print(x, y)
i=0
for item in possibilities[x][y]:
if item !=0.:
for a in range(9):
if (a, y) != (x, y):
possibilities[a][y][i]=0
for a in range(9):
if (x, a) != (x, y):
possibilities[x][a][i]=0
i+=1
def rows_cols_two_strike():
pass
def check_solved():
new_solves = 0
for x in range(9):
for y in range(9):
if solved[x][y] == 0:
temp = set(possibilities[x][y])
solved[x][y] = 1
new_solves += 1
return new_solves
def row_elims():
pass
def complex_solves():
row_elims()
while(True):
#cheap logic goes here
square_elim()
rows_cols()
new_solves = check_solved()
#more expensive logic goes here...
if new_solves == 0:
complex_solves()
new_solves = check_solved()
if new_solves == 0:
print('Finished playing. Either got stuck or won.')
print(solved)
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment