Commit 122091d7 authored by Vít Novotný's avatar Vít Novotný
Browse files

added example 6.3_14

parent 36a8866b
% 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.
#!/usr/bin/env python
# encoding=utf-8 (pep 0263)
# je zapotrebi nainstaloval balicek python-constraint
from constraint import Problem
from linked_lists import LinkedList, Nil
def queens(n):
problem = Problem()
domain = range(n+1)[1:]
variables = LinkedList(list("X%d" % i for i in range(n+1)[1:]))
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():")
for solution in queens(4).getSolutions():
print(solution)
CLP - Problem N dam
Vysledek volani queens(4).getSolutions():
{'X2': 1, 'X3': 4, 'X1': 3, 'X4': 2}
{'X2': 4, 'X3': 1, 'X1': 2, 'X4': 3}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment