Guest User

Untitled

a guest
Aug 15th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.22 KB | None | 0 0
  1. :- dynamic gridsize/2.
  2.  
  3. generate(N, Out) :-
  4.     Size is N*N,
  5.    
  6.     retractall(gridsize(_,_)),
  7.     assertz(gridsize(N,N)),
  8.  
  9.     length(Out, Size).
  10.  
  11. coordsToIndex(X, Y, Index) :-
  12.     gridsize(Width, _),
  13.     Index is Y*Width+X.    
  14.  
  15. indexToCoords(Index, X, Y) :-
  16.     gridsize(Width,_),
  17.  
  18.     Y is (Index div Width),
  19.     X is (Index mod Width).
  20.  
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22.  
  23. put(Grid, Index) :-
  24.     nth0(Index, Grid, h).
  25.  
  26. work(_, _, 0) :- !.
  27. work(_, -1, _) :- !, fail.
  28.  
  29. work(Grid, Index, Remaining) :-
  30.     NewIndex is Index - 1,
  31.     NewRem is Remaining - 1,
  32.  
  33.     (
  34.         (
  35.             check(Grid, Index),
  36.             put(Grid, Index),
  37.             work(Grid, NewIndex, NewRem)        
  38.         );
  39.         work(Grid, NewIndex, Remaining)
  40.     ).
  41.  
  42.    
  43.  
  44. %%%%%%%%%%%%%%%%%%%%%%%%%%
  45.  
  46. check(Grid, Index) :-
  47.     indexToCoords(Index, X, Y),
  48.  
  49.     findall(I, (
  50.         nth0(I, Grid, H), nonvar(H),
  51.         indexToCoords(I, IX, IY),
  52.  
  53.         (
  54.             IX = X;
  55.             IY = Y;
  56.             (abs(IX-X, O), abs(IY-Y, O))
  57.         )
  58.     ), All),
  59.  
  60.     length(All, 0).
  61.  
  62. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  63.  
  64. run(N, Out) :-
  65.     S is N*N - 1,
  66.     generate(N, Out),
  67.     work(Out, S, N).
Add Comment
Please, Sign In to add comment