%% N-Queens Example 1
%% Date: 15/10/2008

solution(X) :- permute([1,2,3,4,5], X), safe(X).

safe([]).
safe([Queen | Others]) :- safe(Others),
                          noattack(Queen, Others, 1).

noattack(Queen, [], XPosition).
noattack(Y, [Y1 | Rest], Xdist) :- Y1 - Y =\= Xdist,
                                   Y - Y1 =\= Xdist,
                                   Dist is Xdist + 1,
                                   noattack(Y, Rest, Dist).

permute([], []).
permute([X | L], P) :- permute(L, L1), insert(X, L1, P).

insert(X, Y, [X | Y]).
insert(X, [Y1 | Y2], [Y1 | Z]) :- insert(X, Y2, Z).