Vrac - resolution of sudoku with python
I try to program an algorithm to resolve a sudoku. They are three process : scanning, marking up and analysis. For now, I've just program scanning and marking up a brut algorithm.
# -*- coding: utf-8 -*-
"""commencé le 18/09/08"""
"""fonctionnel le 23/09/08"""
"""les variables globales:
x et y sont les coordonnées de la case courante
n est la valeur de la case courante"""

sudoku=[[0,0,4,1,0,8,0,0,0],
[0,0,0,3,0,0,0,9,0],
[0,0,0,0,2,0,0,4,5],
[0,0,0,0,0,1,0,0,2],
[0,2,7,0,0,0,0,0,0],
[0,3,0,0,0,0,0,6,0],
[1,0,0,0,5,0,8,0,0],
[0,6,3,0,0,0,9,0,0],
[0,0,9,2,0,0,0,0,3]]

"""construction de la liste des cases vides
list_case est une liste de [x,y]"""
list_case=[]

for i in range(9):
for j in range(9):
if not(sudoku[i][j]):
list_case.append([i,j])

def validite_d_une_case():
global n,x,y,sudoku

"""on test la validité de la case active dans les trois zones"""
ligne = True
colonne = True
carre = True

for i in range(9):
"""dans la ligne"""
if i!=y and n==sudoku[x][i]:
ligne = False
break
if not(ligne):
return False

for i in range(9):
"""dans la colonne"""
if i!=x and n==sudoku[i][y]:
colonne = False
break
if not(colonne):
return False

"""dans le carre"""
# print "x=",x,"y=",y,
c_x = x/3
c_y = y/3
l_x = x%3
l_y = y%3
for i in range(3):
# print "i=", i,
for j in range(3):
# print "j=", j
if i%3!=l_x and j%3!=l_y:
# print "i%3=",i%3,"l_x=",l_x,"j%3=",j%3,"l_y=",l_y
# print "sudoku[c_x + i][c_y + j]=",sudoku[c_x + i][c_y + j]
if sudoku[c_x * 3 + i][c_y * 3 + j] == n:
carre = False
if not(carre):
return False

return True

"""algorythme de résolution"""
len_list_case = len(list_case)
id_case_in_list_case = 0

while id_case_in_list_case < len_list_case:

x = list_case[id_case_in_list_case][0]
y = list_case[id_case_in_list_case][1]

if sudoku[x][y] == 9:
if id_case_in_list_case > 0:
sudoku[x][y] = 0
id_case_in_list_case -=1

x = list_case[id_case_in_list_case][0]
y = list_case[id_case_in_list_case][1]

for n in range(sudoku[x][y]+1,10):
sudoku[x][y]=n

if validite_d_une_case():
id_case_in_list_case += 1
break
elif n == 9:
sudoku[x][y]=0
id_case_in_list_case -=1
break

for i in sudoku:
print i
http://en.wikipedia.org/wiki/Sudoku

Creation date : 15/09/2008 @ 12:36
Last update : 23/09/2008 @ 12:47
Category : Vrac


Preview Preview     Print the article Print the article


Follow me on my new blog : Lascapi.fr


Articles

Close 2d

Close 3d

Close Contest

Other

Close Guppy

Close Vrac

Seek




^ Top ^