#!/usr/bin/env python
# encoding=utf-8 (pep 0263)
from linked_lists import Cons, Nil
def solution(n=8):
if n == 0:
yield Nil
else:
for others in solution(n-1):
x = 9 - n
for y in range(1, 9):
if noattack(x, y, others):
yield Cons((x, y), others)
def noattack(x, y, others):
if others == Nil:
return True
else:
x1, y1 = others.head
return x != x1 and y != y1 and y1-y != x1-x and y1-y != x-x1 and \
noattack(x, y, others.tail)
# demonstracni vypis
if __name__ == "__main__":
print("PROBLEM OSMI DAM I")
print("Volani next(solution()) : %s" % next(solution()))
PROBLEM OSMI DAM I
Volani next(solution()) : [(1, 4), (2, 2), (3, 7), (4, 3), (5, 6), (6, 8), (7, 5), (8, 1)]
| % nacteni:
/* ['3.2_4.pl']. */
solution(S) :- template(S), sol(S).
sol([]).
sol([X/Y|Others]) :- sol(Others), member(Y,[1,2,3,4,5,6,7,8]),
noattack(X/Y,Others).
noattack(_,[]).
noattack(X/Y,[X1/Y1|Others]) :- X=\=X1, Y=\=Y1, Y1-Y=\=X1-X, Y1-Y=\=X-X1,
noattack(X/Y,Others).
template([1/_Y1,2/_Y2,3/_Y3,4/_Y4,5/_Y5,6/_Y6,7/_Y7,8/_Y8]).
% demonstracni vypis
start:-
write('PROBLEM OSMI DAM II - jeden sloupec pro kazdou damu'),nl,
write('Prvni reseni solution(Solution) - vsimnete si zrychleni oproti verzi I:'),nl,
solution(Solution),write(Solution),nl.
?-start.
PROBLEM OSMI DAM II - jeden sloupec pro kazdou damu
Prvni reseni solution(Solution) - vsimnete si zrychleni oproti verzi I:
[1/4,2/2,3/7,4/3,5/6,6/8,7/5,8/1]
|