Advertisement
JosepRivaille

LI - Squares

Jun 23rd, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 2.25 KB | None | 0 0
  1. :- use_module(library(clpfd)).
  2.  
  3. %ejemplo(_, Big, [S1...SN]): how to fit all squares of sizes S1...SN in a square of size Big?
  4. ejemplo(0,   3, [2,1,1,1,1,1]).
  5. ejemplo(1,   4, [2,2,2,1,1,1,1]).
  6. ejemplo(2,   5, [3,2,2,2,1,1,1,1]).
  7. ejemplo(3,  19, [10,9,7,6,4,4,3,3,3,3,3,2,2,2,1,1,1,1,1,1]).
  8. ejemplo(4, 112, [50,42,37,35,33,29,27,25,24,19,18,17,16,15,11,9,8,7,6,4,2]).
  9. ejemplo(5, 175, [81,64,56,55,51,43,39,38,35,33,31,30,29,20,18,16,14,9,8,5,4,3,2,1]).
  10.  
  11. doExample(E) :-
  12.     ejemplo(E, Big, Sides),
  13.     nl, write('Fitting all squares of size '), write(Sides), write(' into big square of size '), write(Big), nl,nl,
  14.     length(Sides, N),
  15.     length(RowVars, N), % get list of N prolog vars: Row coordinates of each small square
  16.     length(ColVars, N), % get list of N prolog vars: Col coordinates of each small square
  17.     RowVars ins 1..Big,
  18.     ColVars ins 1..Big,
  19.     insideBigSquare(N, Big, Sides, RowVars),
  20.     insideBigSquare(N, Big, Sides, ColVars),
  21.     nonoverlapping(N, Sides, RowVars, ColVars),
  22.     append(RowVars, ColVars, Vars),
  23.     label(Vars),
  24.     displaySol(N, Sides, RowVars, ColVars).
  25.  
  26. insideBigSquare(_, _, [], []) :- !.
  27. insideBigSquare(N, Big, [S|Sides], [V|Vars]) :-
  28.     V + S - 1 #=< Big, insideBigSquare(N, Big, Sides, Vars).
  29.  
  30. nonoverlapping(1, _, _, _) :- !.
  31. nonoverlapping(N, [S|Sides], [R|RowVars], [C|ColVars]) :-
  32.     squareRCSnoOverlapsL(S, R, C, Sides, RowVars, ColVars),
  33.     NP is N - 1, nonoverlapping(NP, Sides, RowVars, ColVars).
  34.  
  35. squareRCSnoOverlapsL(_, _, _, [], [], []) :- !.
  36. squareRCSnoOverlapsL(S, R, C, [SP|Sides], [RP|RowVars], [CP|ColVars]) :-
  37.     RP #>= R + S #\/ RP + SP #=< R #\/ CP #>= C + S #\/ CP + SP #=< C,
  38.     squareRCSnoOverlapsL(S, R, C, Sides, RowVars, ColVars).
  39.  
  40. displaySol(N, Sides, RowVars, ColVars):-
  41.     between(1, N, Row), nl, between(1, N, Col),
  42.     nth1(K, Sides, S),
  43.     nth1(K, RowVars, RV), RVS is RV + S - 1, between(RV, RVS, Row),
  44.     nth1(K, ColVars, CV), CVS is CV + S - 1, between(CV, CVS, Col),
  45.     writeSide(S), fail.
  46. displaySol(_,_,_,_):- nl.
  47.  
  48. writeSide(S):- S < 10, write('  '), write(S), !.
  49. writeSide(S):- write(' '), write(S), !.
  50.  
  51. main:-
  52.     doExample(0),
  53.     doExample(1),
  54.     doExample(2),
  55.     doExample(3),
  56.     doExample(4),
  57.     doExample(5),
  58.     halt.
  59.  
  60. % JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement