Last active
July 21, 2020 17:10
-
-
Save oisincar/963a5a941ba0df470dc788486786e7da to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from constraint import * | |
# board = [ | |
# "1 | 48| ", | |
# " 6| |831", | |
# " | 5| 6 ", | |
# # - | |
# " 5| |7 9", | |
# " |5 7| ", | |
# "6 8| |1 ", | |
# # - | |
# " 3 |7 | ", | |
# "567| |9 ", | |
# " |42 | 5"] | |
# board = [ | |
# " | | ", | |
# " | | ", | |
# " | | ", | |
# # - | |
# " | | ", | |
# " 5 | | ", | |
# " | | ", | |
# # - | |
# " 2| | ", | |
# " | | ", | |
# " |7 | 3"] | |
board = [ | |
" | | ", | |
" | | ", | |
" | | ", | |
# - | |
" | | ", | |
" | | ", | |
" | | ", | |
# - | |
" | | ", | |
" | | ", | |
" | | "] | |
# a string with 81 chars: | |
board2 = "".join([row.replace("|", "") for row in board]) | |
def print_board(b): | |
print("-------------") | |
for i in range(9): | |
for j in range(9): | |
print(b[i*9 + j], end="") | |
print() | |
print() | |
problem = Problem() | |
# 81 variables, each 1-9 | |
for i in range(81): | |
if board2[i] == " ": | |
# Unknown: | |
problem.addVariable(i, range(1,10)) | |
else: | |
v = int(board2[i]) | |
problem.addVariable(i,[v]) | |
# Add constant single values, useful for siteswap calculations | |
# cause otherwise stupid bs happens | |
for i in range(9): | |
problem.addVariable(100+i, [i]) | |
# Make sure the variables in coords array form a valid siteswap. | |
def add_siteswap_const(coords): | |
# indices to add constraint to in the given array | |
for i1 in range(9): | |
for i2 in range(i1+1, 9): | |
# Add constraint to variables at index coords[i1] and coords[i2]... | |
# The difference in these must not equal their distance in the siteswap, | |
# mod 9 or something. | |
problem.addConstraint(lambda a, b, diff: (a-b) % 9 != diff, | |
(coords[i1], coords[i2], 100+i2-i1)) | |
for j in range(9): | |
# columns different | |
problem.addConstraint(AllDifferentConstraint(), range(j*9, (j+1)*9)) | |
# colums are sss | |
add_siteswap_const([i for i in range(j*9, (j+1)*9)]) | |
# rows different | |
problem.addConstraint(AllDifferentConstraint(), range(j, 81, 9)) | |
# rows are sss | |
add_siteswap_const([i for i in range(j, 81, 9)]) | |
# boxes different | |
for i_b in range(0, 9, 3): | |
for j_b in range(0, 9, 3): | |
# uhh, now we've the top left corner of a box... | |
# All the coords of squares in that box: | |
vals = [d + i_b*9 + j_b for d in [0,1,2, 9,10,11, 18,19,20]] | |
problem.addConstraint(AllDifferentConstraint(), vals) | |
i = 0 | |
for sol in problem.getSolutionIter(): | |
i += 1 | |
if i % 100 == 0: | |
print(i) | |
print_board(sol) | |
# print_board(problem.getSolution()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment