Skip to content

Instantly share code, notes, and snippets.

@hirotnk
Created January 14, 2011 21:56
Show Gist options
  • Save hirotnk/780337 to your computer and use it in GitHub Desktop.
Save hirotnk/780337 to your computer and use it in GitHub Desktop.
8 Queen solver
% eightqueen.pro
%
nocheck(_,[]).
nocheck(X/Y, [X1/Y1 | Rest]) :- X=\=X1,Y=\=Y1,
abs(Y1-Y) =\= abs(X1-X),
nocheck(X/Y,Rest).
legal([]).
legal([X/Y | Rest]) :-
legal( Rest),
% member(X,[1,2,3,4,5,6,7,8]),
member(X,[1,2,3,4,5,6,7,8]),
nocheck(X/Y,Rest).
if(Test,Then) :- Test,!,Then.
if(_,_,Else) :- Else.
manual(X) :- write('ls: list the solutions
cn: output the number of solutions
mp; display mapping on the board for solutions
\n
Enter Command:'),
read(X),
write('You enter:'), write(X), nl.
eightqueens :- manual(CMD),
eightqueens_body(CMD).
eightqueens_body(CMD) :-
CMD == 'mp',findall( X, eightqueens_map(X), L),
len(L,N),write('There are '),write(N),write(' solutions.').
eightqueens_body(CMD) :-
CMD == 'ls',findall( X, eightqueens_list(X), L),
showlist3(L,1), len(L,N),write('There are '),write(N),write(' solutions.').
eightqueens_body(CMD) :-
CMD == 'cn',findall( X, eightqueens_cnt(X), L),
len(L,N),write('There are '),write(N),write(' solutions.').
eightqueens_map(X) :-
X = [_/1,_/2,_/3,_/4,_/5,_/6,_/7,_/8],
legal(X),
showlist(X),
write('['),tab(1),
showlist2(X).
eightqueens_list(X) :-
X = [_/1,_/2,_/3,_/4,_/5,_/6,_/7,_/8],
legal(X).
%legal(X),
%write('['),
%showlist3(X).
eightqueens_cnt(X) :-
X = [_/1,_/2,_/3,_/4,_/5,_/6,_/7,_/8],
legal(X).
showlist([]) :- nl.
showlist([X|Y]) :- X = C/_, showboard(C,8), showlist(Y).
showlist2([]) :- write(']\n\n\n').
showlist2([X|Y]) :- write(X), tab(1), showlist2(Y).
showlist3([],0) :- nl.
showlist3([X|Y],N) :- N1 is N + 1, write(N), tab(1), write('['), showlist2(X), showlist3(Y,N1).
showboard(X,N) :- X = 0, write('Q|'), N1 is N -1, showboard2(N1).
showboard(X,N) :- X > 0, write(' |'), X1 is X - 1, N1 is N -1, showboard(X1,N1).
showboard2(N) :- N < 0, write('\n').
showboard2(N) :- N = 0, write(' |'),N1 is N -1, showboard2(N1).
showboard2(N) :- N > 0, write(' |'),N1 is N - 1, showboard2(N1).
len([],0) :- nl.
len([_|T], N) :- len(T, N1), N is 1 + N1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment