I am trying to understand how this n-queens Prolog solution from N-Queens Problem..How far can we go? works (there were no comments on the original page). I have tried to add comments where I could understand something:
generate([],_). % A LIST BEING GENERATED
generate([H|T],N) :-
H in 1..N , % NOT CLEAR IF IT INCLUDES ALL COMBINATIONS OR PERMUTATIONS
generate(T,N).
lenlist(L,N) :-
lenlist(L,0,N).
lenlist([],N,N).
lenlist([_|T],P,N) :-
P1 is P+1,
lenlist(T,P1,N).
queens(N,L) :- % MAIN FN: SEND NUMBER OF QUEENS AND GET ANSWER LIST OF LISTS
generate(L,N),lenlist(L,N), % GENERATE LIST BASED ON N OF ALL COMBINATIONS
safe(L), % CHECK WHICH ONES ARE SAFE (NON-ATTACKING)
!,
labeling([ffc],L). % CHOOSE CORRECT ONES (WHY NEEDED IF ALREADY FOUND SAFE?)
notattack(X,Xs) :- % FNS TO FIND QUEENS NOT ATTACKING
notattack(X,Xs,1).
notattack(X,[],N).
notattack(X,[Y|Ys],N) :-
X #\= Y,
X #\= Y - N,
X #\= Y + N,
N1 is N + 1,
notattack(X,Ys,N1).
safe([]). % RECURSIVE FN TO FIND LISTS WITH NON-ATTACKING QUEENS
safe([F|T]) :-
notattack(F,T),
safe(T).
I am far from clear how is the initial list being generated. Is it an all permutation list or only a random list? Moreover, why both safe and labeling functions are needed? Thanks for your help in advance.