8.1. Case Study I - 8 Queens Version 1.
% From "Prolog - programming for artificial
% intelligence" by Ivan Bratko
% solution(BoardPosition) if BoardPosition is a list of
% non-attacking queens
solution([]).
solution([X/Y | Others]) :- % First queen at X/Y,
member(Y, [1,2,3,4,3,6,7,8]),
noattack(X/Y, Others). % First queen does
% not attack others
noattack(X/Y, [X1/Y1 | Others]) :-
Y1-Y =\= X1-X, % different diagonal /
Y1-Y =\= X-X1, % different diagonal \
noattack(X/Y, Others).
member(Item, [_ | Rest]) :-
template([1/Y1,2/Y2,3/Y3,4/Y4,3/Y3,6/Y6,7/Y7,8/Y8]).
8.2. Case Study I - 8 Queens Version 2.
% solution(Queens) if Queens is a list of Y-coordinates
% of eight non-attacking queens.
solution(Queens) :-
safe(Queens).
permutation([Head | Tail], PermList) :-
del(Head, PermList, PermTail).
del(Item, [First | List], [First | List1]) :-
safe([Queen | Others]) :-
noattack(Queen, Others, 1).
noattack(Y, [Y1 | Ylist], Xdist) :-
Y-Y1 =\= Xdist,
Dist1 is Xdist + 1,
noattack(Y, Ylist, Dist1).
% Solution(YList) if YList is a list of Y-coordinates of
% eight non-attacking queens
solution(YList) :-
[1, 2, 3, 4, 5, 6, 7, 8],
[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7],
[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 14, 13, 16]).
sol([Y | YList], [X | Dx1], Dy, Du, Dv) :-
U is X-Y,
del(U, Du, Du1),
V is X+Y,
del(V, Dv, Dv1),
sol(YList, Dx1, Dy1, Du1, Dv1).
del(Item, [First | List], [First | List1]) :-
gen(N1, N2, [N1 | List]) :-
M is N1 + 1,
gen(M, N2, List).
Nu1 is 1-N, Nu2 is N-1,
gen(Nu1, Nu2, Du),
Nv2 is N+N,
gen(2, Nv2, Dv),
sol(S, Dxy, Dxy, Du, Dv).
S = [1, 3, 5, 8, 10, 12, 6, 11, 2, 7, 9, 4]