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,

noattack(_, []). % nothing to attack

noattack(X/Y, [X1/Y1 | Others]) :-

member(Item, [Item | _]).

member(Item, [_ | Rest]) :-

% A solution template

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) :-

permutation([], []).

permutation([Head | Tail], PermList) :-

del(Item, [Item | List], List).

del(Item, [First | List], [First | List1]) :-

safe([]).

safe([Queen | Others]) :-

noattack(_, [], _).

noattack(Y, [Y1 | Ylist], Xdist) :-

8.3. Case Study I - 8 Queens Version 3.

% Solution(YList) if YList is a list of Y-coordinates of

% eight non-attacking queens

solution(YList) :-

sol([], [], Dy, Du, Dv).

sol([Y | YList], [X | Dx1], Dy, Du, Dv) :-

del(Item, [Item | List], List).

del(Item, [First | List], [First | List1]) :-

8.4. Generalisation to N queens
  • To generalise example 3 to N queens we need to generate the domains automatically.
  • Need a procedure
  • which for two given integers produces a list
  • Such a procedure is
  • The top level solution can then be generalized to
  • where N is the size of the board and S is the list of Y-coordinates for a valid solution.
  • General solution is
  • and to obtain a solution (eg 12 queens) try