Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.79 KB | None | 0 0
  1. % The Postage Stamp Problem
  2. % Running GNU Prolog 1.3.1 on Windows 7
  3. % Given the maximum number of stamps and a set of stamp denominations
  4. % This program should print to screen the maximum amount of coverage
  5. % that the denominations can fill on an envelope
  6. % so if you have test(1, 5, [1, 4, 12, 21]).
  7. % 1 is the test case; 5 is the max stamps on the envelope
  8. % 1, 4, 12, 21 are the stamp denominations
  9. % That would return 71, as 72 can not be created with a max size of 5
  10. % allowed stamps on the envelope.
  11. % Finds max value in sequence 1,...,n per problem instance.
  12. % Fails if no such number exists.
  13.  
  14. test(1, 5, [1, 4, 12, 21]).      % from in01.txt
  15. test(2, 10, [1, 7, 16, 31, 88]). % from in01.txt
  16. test(3, 6, [1, 5, 7, 8]).        % from in01.txt
  17. test(4, 5, [1, 4]).              % from in02.txt
  18. test(5, 6, [1, 2, 3, 7, 11]).    % from in03.txt
  19. test(6, 7, [1, 5, 9]).           % from in03.txt
  20. test(7, 6, [2, 3, 7, 11]).       % from in05.txt
  21. test(8, 7, [5, 9]).              % from in05.txt
  22. test(9, 10, [1]).                % from in06.txt
  23. test(10, 10, [1, 3]).            % from in06.txt
  24.  
  25. runtest(N, C) :- test(N, Width, Stamps), maxcoverage(C, Width, Stamps).
  26.  
  27. maxcoverage(StampsCount, Stamps, Max):-
  28.     maxcoverage(0, StampsCount, Stamps, Max),
  29.     Max > 0.
  30.  
  31. maxcoverage(Previous, StampsCount, Stamps, Max):-
  32.     Current is Previous + 1,
  33.     (realize(StampsCount, Stamps, Current) ->       % Tries current value.
  34.         maxcoverage(Previous, StampsCount, Stamps, Max) % When succeeds, tries more.
  35.     ;
  36.         Max = Previous                              % Else returns prvious value as max.
  37.     ).
  38. realize(StampsCount, Stamps, Value):-
  39.     (Value = 0 ->
  40.         true
  41.     ;
  42.         StampsCount > 0,
  43.         Value > 0,
  44.         member(Stamp, Stamps),
  45.         ValCount is Value - Stamp,
  46.         VValue is Value - 1,
  47.         realize(VValue, Stamps, ValCount)
  48.     ).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement