8 queens

Description

A CLP(FD) program for eight queens.

Source: PROLOG programming for artificial intelligence, 3rd Edition, Harlow, 2001, ISBN 0-201-40375-7.

Download

Program source code: 8_queens.pl

Listing

%  Figure 14.9  A CLP(FD) program for eight queens.
 
 
% 8 queens in CLP(FD)
 
solution( Ys)  :-             % Ys is list of Y-coordinates of queens
  Ys = [_,_,_,_,_,_,_,_],     % There are 8 queens
  domain( Ys, 1, 8),          % All the coordinates have domains 1..8
  all_different( Ys),         % All different to avoid horizontal attacks
  safe( Ys),                  % Constrain to prevent diagonal attacks
  labeling( [], Ys).          % Find concrete values for Ys
 
safe( []).
 
safe( [Y | Ys])  :-
  no_attack( Y, Ys, 1),       % 1 = horizontal distance between queen Y and Ys
  safe( Ys).
 
% no_attack( Y, Ys, D):
%   queen at Y doesn't attack any queen at Ys; 
%   D is column distance between first queen and other queens
 
no_attack( Y, [], _).
 
no_attack( Y1, [Y2 | Ys], D)  :-
  D \= Y1-Y2,
  D \= Y2-Y1,
  D1 is D+1,
  no_attack( Y1, Ys, D1).

Comments

pl/prolog/pllib/8_queens.txt · ostatnio zmienione: 2017/07/17 08:08 (edycja zewnętrzna)
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0