leo3065

[Prolog] Magic square

Oct 27th, 2018
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.37 KB | None | 0 0
  1. :- use_module(library(yall)).
  2. :- use_module(library(clpfd)).
  3.  
  4. create_mat(0, _, []).
  5. create_mat(N0, N, [Zeile|Matrix]) :-
  6.         N0 > 0,
  7.         N1 is N0 - 1,
  8.         length(Zeile, N),
  9.         create_mat(N1, N, Matrix).
  10.  
  11. sum_row([], _).
  12. sum_row([Row|Matrix], SumDim) :-
  13.         sum(Row, #=, SumDim),
  14.         sum_row(Matrix, SumDim).
  15.  
  16. diag1([], _, _, []).
  17. diag1([Row|Matrix], Idx, P, [X|ListeDiag]) :-
  18.         nth1(Idx, Row, X),
  19.         Idx1 is Idx+P,
  20.         diag1(Matrix, Idx1, P, ListeDiag).
  21.  
  22. magic_square(N, Matrix) :-
  23.         Nmax is N * N,
  24.         SumDim is N * (N * N + 1) / 2,
  25.         create_mat(N, N, Matrix),
  26.         flatten(Matrix, Vars),
  27.         Vars ins 1..Nmax,
  28.         all_different(Vars),
  29.         sum_row(Matrix, SumDim),
  30.         transpose(Matrix, TransMat),
  31.         sum_row(TransMat, SumDim),
  32.         diag1(Matrix, N, -1, D1),
  33.         sum(D1, #=, SumDim),
  34.         diag1(Matrix, 1, +1, D2),
  35.         sum(D2, #=, SumDim).
  36.        
  37. solve(N,M) :-
  38.         magic_square(N,M),
  39.         flatten(M,V),
  40.         labeling([ff],V).
  41.  
  42. findpos(N,L,Bag):-
  43.         create_mat(N,N,M),
  44.         flatten(M,V),
  45.         length(L,Z),
  46.         findall([P,Count],(
  47.                 length(P,Z),
  48.                 maplist({V}/[X,Y]>>nth1(X,V,Y),P,L),
  49.                 aggregate_all(count, solve(N,M), Count),
  50.                 Count \= 0
  51.                 ),
  52.         Bag).
Advertisement
Add Comment
Please, Sign In to add comment