Skip to content

Instantly share code, notes, and snippets.

@tonyromarock
Last active April 28, 2024 23:55
Show Gist options
  • Save tonyromarock/34168259b0fb779a2ef7 to your computer and use it in GitHub Desktop.
Save tonyromarock/34168259b0fb779a2ef7 to your computer and use it in GitHub Desktop.
Using Python-Constraint to solve the eight queens puzzle
#!/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
@cykrr
Copy link

cykrr commented Apr 28, 2024

n = int(sys.argv[1])
for i in range(n):
    p.addVariable(i, range(n))

for i in range(n-1):
    for j in range(i+1, n):
        p.addConstraint(lambda qi, qj, i=i, j=j:
                        qi != qj and
                        abs(qi - qj) != j - i,
                         (i, j))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment