%:- use_module(library(clpfd)).

queens(N, Queens) :-
     statistics(runtime,_),
     vincola(Queens,N),   %%% constraint    
     statistics(runtime,[_,T1]),
     format("Start searching~n",[]),
     labeling([ff,split], Queens), %%% generate
     statistics(runtime,[_,T2]),
     format("Solution found in ~d + ~d ms ~n",[T1,T2]).

vincola(Queens,N) :-
     length(Queens, N),
     domain(Queens,1,N), %%% Queens :: 1..N
     all_different(Queens),
     %tuttedifferenti(Queens),
     %all_distinct(Queens), %%% Orizzontali
     diagonal(Queens). %%% Diagonali

diagonal([]).
diagonal([Q|Queens]) :-
    sicure(Q, 1, Queens),
    diagonal(Queens).

sicure(_,_,[]).
sicure(X,D,[Q|Queens]) :-
    nonattacca(X,Q,D),
    D1 is D+1,
    sicure(X,D1,Queens).

nonattacca(X,Y,D) :-
     X + D #\= Y,
     Y + D #\= X.
     
tuttedifferenti([]) :- !.     
tuttedifferenti([_]) :- !.     
tuttedifferenti([A|R]) :- 
    differenti(A,R),
    tuttedifferenti(R).
differenti(_,[]).
differenti(A,[B|R]) :-
    A #\= B,
    differenti(A,R).
         
     
