avejidah

Eight Queens solver

Mar 7th, 2013
430
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 0.97 KB | None | 0 0
  1. %---
  2. % Revision 3 of the queens solver.
  3. %---
  4.  
  5. % A solved board is a board that has a piece in every row, and no piece
  6. % intersects any other (no rows are shared and no diagonals are shared).
  7. solvedBoardPerm(X) :- boardPerm(X), noIntersect(X).
  8. boardPerm([A,B,C,D,E,F,G,H]) :- row(A),row(B),row(C),row(D),row(E),row(F),row(G),row(H).
  9. row(A) :- between(0,7,A).
  10.  
  11. % The head doesn't intersect anything in the tail, and there are no
  12. % intersections in the tail.
  13. noIntersect([]).
  14. noIntersect([Head | Tail]) :- noIntersect(Head, Tail, 1), noIntersect(Tail).
  15.  
  16. noIntersect(_, [], _).
  17. noIntersect(Ele, [Head | Tail], DiagOffset) :-
  18.   Ele \= Head, % The row is not shared.
  19.   PosDiag is Head - DiagOffset,  Ele \= PosDiag, % The positive diagonal is not shared.
  20.   NegDiag is Head + DiagOffset,  Ele \= NegDiag, % The negative diagonal is not shared.
  21.   % The element doesn't intersect anything in the tail.
  22.   NextDiagOffset is DiagOffset + 1, noIntersect(Ele, Tail, NextDiagOffset).
Advertisement
Add Comment
Please, Sign In to add comment