next up previous index
Next: Program Source Modifications Up: Grace 1.0 User Previous: Constraint Programs

Starting with Grace

This chapter provides a quick introduction to basic Grace features.

Let us start with a simple example, the well known N-queens puzzle. This is not a terribly useful problem, however it is quite easy to program and its execution is nontrivial, which is exactly what we need to show what can be done with Grace . A FD program queens.pl to solve the puzzle might look as follows:

%
% The N-queens puzzle. We have to place N queens on an NxN chess boards
% so that no-one can take another one. Our model is:
%
%        Variables: N variables with domain 1..N, each variable represents
%                        the position of a queen in one column
%        Constraints:
%                1) all columns are different - IMPLICIT
%                2) all rows are different
%                3) no diagonal has more than one queen
%

:- lib(fd).

queens(N, List) :-

    % Define variables and their domains
    length(List, N),
    List :: 1..N,

    % Constraints
    %2
    alldistinct(List),
    %3
    constrain_queens(List),

    % Label the variables
    labeling(List).

% A queen is safe if it cannot be taken by
% any of its right-hand neigbours
constrain_queens([]).
constrain_queens([X|Y]) :-
   safe(X, Y, 1),
   constrain_queens(Y).

safe(_, [], _).
safe(Q1, [Q2|T], N) :-
   % Q1 and Q2 are not on the same diagonal
   Q1 - Q2 #\= N,
   Q2 - Q1 #\= N,
   N1 is N + 1 ,
   safe(Q1, T, N1).

labeling([]).
labeling([X|L]) :-
    indomain(X),
    labeling(L).

When we run it, we get the expected results

[eclipse 46]: queens(8, L).

L = [1, 5, 8, 6, 3, 7, 2, 4]     More? (;) 

L = [1, 6, 8, 3, 7, 4, 2, 5]     More? (;) 

L = [1, 7, 4, 6, 8, 2, 5, 3]     More? (;) 

L = [1, 7, 5, 8, 2, 4, 6, 3]     More? (;) 

...




Micha Meier
Tue Jul 2 10:07:34 MET DST 1996