coin_change.pl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 14 November 2015
  4. # Edit: 15 May 2021
  5. # https://github.com/trizen
  6. # The classic coin-change problem.
  7. use 5.010;
  8. use strict;
  9. use warnings;
  10. use List::Util qw(sum0);
  11. no warnings qw(recursion);
  12. my @denominations = (.01, .05, .1, .25, .5, 1, 2, 5, 10, 20, 50, 100);
  13. sub change {
  14. my ($n, $pos, $solution) = @_;
  15. my $sum = sum0(@$solution);
  16. if ($sum == $n) {
  17. return $solution; # found a solution
  18. }
  19. elsif ($sum > $n or $pos > $#denominations) {
  20. return;
  21. }
  22. (
  23. change($n, $pos + 1, $solution),
  24. change($n, $pos, [@$solution, $denominations[$pos]]),
  25. )
  26. }
  27. my $amount = 0.26; # the amount of money
  28. my @solutions = change($amount, 0, []);
  29. print("All the possible solutions for $amount, are:\n");
  30. my $best = $solutions[0];
  31. foreach my $s (@solutions) {
  32. # Print the solutions
  33. print("\t[" . join(", ", @{$s}) . "]\n");
  34. # Find the best solution (which uses the minimum number of coins)
  35. if (@$s < @$best) {
  36. $best = $s;
  37. }
  38. }
  39. print("The best solution is: [", join(", ", @$best) . "]\n");