#!/usr/bin/env python
# encoding=utf-8 (pep 0263)
# je zapotrebi nainstalovat balicek python-constraint
from constraint import Problem
from linked_lists import LinkedList, Nil
def queens(n):
    problem = Problem()
    domain = range(1,n+1)
    variables = LinkedList(list("X%d" % i for i in domain))
    for name in variables:
        problem.addVariable(name, domain)
    constr_all(problem, variables)
    return problem
def constr_all(problem, variables):
    if variables == Nil:
        return
    x = variables.head
    xs = variables.tail
    constr_between(problem, x, xs, 1)
    constr_all(problem, xs)
def constr_between(problem, x, other_variables, n):
    if other_variables == Nil:
        return
    y = other_variables.head
    ys = other_variables.tail
    no_threat(problem, x, y, n)
    constr_between(problem, x, ys, n + 1)
def no_threat(problem, x, y, j):
    problem.addConstraint(lambda x_, y_: x_ != y_ and x_ + j != y_ and x_ - j != y_, (x, y))
# demonstracni vypis
if __name__ == "__main__":
    print("CLP - Problem N dam\n")
    print("Vysledek volani queens(4).getSolutions():")
    print("------")
    for solution in queens(4).getSolutions():
        for key, value in sorted(solution.items()):
            print("%s : %s" % (key, value))
        print("------")
 
  
 CLP - Problem N dam
Vysledek volani queens(4).getSolutions():
------
X1 : 3
X2 : 1
X3 : 4
X4 : 2
------
X1 : 2
X2 : 4
X3 : 1
X4 : 3
------
  |  % nacteni:
/* ['6.3_14.pl']. */
:- retractall(write_all_X/3).
:- retractall(start/0).
:- use_module(library(clpfd)). % clpq , clpr
queens(N,L,Type):- length(L,N),
                   L ins 1..N,
                   constr_all(L),
                   labeling(Type,L).
constr_all([]).
constr_all([X|Xs]):- constr_between(X,Xs,1), constr_all(Xs).
constr_between(_,[],_).
constr_between(X,[Y|Ys],N):- no_threat(X,Y,N),
                             N1 is N+1,
                             constr_between(X,Ys,N1).
                             
no_threat(X,Y,J):- X #\= Y, X+J #\= Y, X-J #\= Y.
:- dynamic
       write_all_X/3,
       start/0.
       
write_all_X(Goal,X,Name):-
            call(Goal),write('  '),write(Name),write(' = '),write(X),nl,fail.
write_all_X(_,_,_).
start:- 
    write('CLP - Problem N dam'),nl,nl,
    write('Vysledek dotazu "queens(4, L, [ff])":'),nl,
    write_all_X(queens(4, L, [ff]), L, 'L').
    
?-start.
 
 CLP - Problem N dam
Vysledek dotazu "queens(4, L, [ff])":
  L = [2,4,1,3]
  L = [3,1,4,2]
  |