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