8 queens 2

Description

Program solves 8 queens problem

Source: PrologTutorial (on-line tutorial)

Download

Program source code: 8_queens_2.pl

Listing

/* prolog tutorial 2.11 Chess queens challenge puzzle */
 
perm([X|Y],Z) :- perm(Y,W), takeout(X,Z,W).   
perm([],[]).
 
takeout(X,[X|R],R).
takeout(X,[F|R],[F|S]) :- takeout(X,R,S).
 
solve(P) :-
     perm([1,2,3,4,5,6,7,8],P), 
     combine([1,2,3,4,5,6,7,8],P,S,D),
     all_diff(S),
     all_diff(D).
 
combine([X1|X],[Y1|Y],[S1|S],[D1|D]) :-
     S1 is X1 +Y1,
     D1 is X1 - Y1,
     combine(X,Y,S,D).
combine([],[],[],[]).
 
all_diff([X|Y]) :-  \+member(X,Y), all_diff(Y).
all_diff([X]).
 
 
/* ?- solve(P).
P = [5,2,6,1,7,4,8,3] ;
P = [6,3,5,7,1,4,2,8] ;
...
 
?- setof(P,solve(P),Set), length(Set,L).
...
L = 92
*/

Comments

pl/prolog/pllib/8_queens_2.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