Monthly Archives: January 2020

N queens in Prolog

:- use_module(library(clpfd)).

n_queens(N, Queens) :-
        length(Queens, N),
        Queens ins 1..N,
	all_different(Queens), %% the queens must be in different columns
        different_diagonals(Queens).

different_diagonals([]).
different_diagonals([Q|Queens]) :- different_diagonals(Queens, Q, 1), different_diagonals(Queens).

different_diagonals([], _, _).
different_diagonals([Q|Queens], Q0, Distance) :-
        abs(Q0 - Q) #\= Distance,
        NewDistance #= Distance + 1,
        different_diagonals(Queens, Q0, NewDistance).

/* 
   Queens is the list of columns of the queens: the corresponding rows are the position of the elements/columns in the list Queens

   Examples:

   ?- n_queens(8, Queens), labeling([ff], Queens).
   %@ Queens = [1, 5, 8, 6, 3, 7, 2, 4] ;
   %@ Queens = [1, 6, 8, 3, 7, 4, 2, 5] .

   The result chess cells are, for instance, [1,1], [2,5], [3,8], [4,6], [5,3], [6,7], [7,2], [8,4]

   Suggestion from https://www.swi-prolog.org/pldoc/man?section=clpfd-n-queens
 */

Prolog and Constraint Logic Programming over Finite Domains

I like Prolog and in these days I have studied the library CLP(FD).

For instance it is easy to write a simple code for solving “How many men and horses have 8 heads and 20 feet?”. You write the rules and contraints and Prolog will find the solution for you

men_and_horses(Men, Horses):-
    Men in 0..10,
    Horses in 0..10,
    Men + Horses #= 8, %% heads must be 8
    Men * 2 + Horses * 4 #= 20. %% feet must be 20

?- men_and_horses(Men, Horses).
 Men = 6,
 Horses = 2.

“clp(fd) is useful for solving a wide variety of find values for these variables problems. Here are some broad categories of problems that clp(fd) can address:

  • Scheduling problems, like, when should we do what work in this factory to make these products?
  • Optimization problems, like which mix of products should we make in this factory to maximize profits?
  • Satisficing problems, like finding an arrangement of rooms in a hospital that meets criteria like having the operating theater near the recovery rooms, or finding a set of vacation plans the whole family can agree on.
  • Sequence problems, like finding a travel itinerary that gets us to our destination.
  • Labeling problems, like Sudoku or Cryptarithm puzzles
  • …. ” [See what_is_clp_fd_good_for]