Last active
March 13, 2016 15:06
-
-
Save tonyromarock/34168259b0fb779a2ef7 to your computer and use it in GitHub Desktop.
Using Python-Constraint to solve the eight queens puzzle
This file contains 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
#!/usr/bin/env python2 | |
from constraint import * | |
problem = Problem() | |
cols = range(1,9) # these are the variables | |
rows = range(1,9) # these are the domains | |
problem.addVariables(cols, rows) # adding multiple variables at once | |
# that each queen has to be in a separate column is | |
# implied through the loop and added constraints | |
for col1 in cols: | |
for col2 in cols: | |
if col1 < col2: | |
problem.addConstraint(lambda row1, row2, col1=col1, col2=col2: | |
abs(row1-row2) != abs(col1-col2) and # this is the diagonal check | |
row1 != row2, (col1, col2)) # this is the horizontal check | |
solution = problem.getSolution() | |
print solution |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment