The Problem: On Venus, the Venusians use coins of these values [1, 6, 10, 19]. Use an algorithm to compute the minimum number of coins needed to make change for 42 on Venus. State which coins are used to satisfy this minimum
I used Dynamic Programming as the algorithm used to solve this problem.
Here my work
1 coin to make 6
2 coins to make 12 (+6)
3 coins to make 13 (+1)
4 coins to make 32 (+19)
5 coins to make 42 (+10)
So my answer would be the minimum number of coins needed to make change for 42 on Venus would be 5 and the coins to satisfy this minimum are {6, 6, 1, 19, 10}
Does everyone agree with my answer(5) and my arrangement of coins to satisfy the minimum 5 or is there a better answer?
I am contributing a Perl script and a table of values up to $57$ for verification purposes. This is the table.
This is the Perl script that I used. It is left as an exercise to the reader to modify this script or possibly use a different programming language so that it collects all minimal solutions rather than just one.
#! /usr/bin/perl -w MAIN: { my @coins = (1, 6, 10, 19); my $upper = shift || 42; my @change = ([]); for(my $q=1; $q <= $upper; $q++){ my ($count, $denom) = ($q+1); foreach my $coin (@coins){ my $rest = $q-$coin; if($rest >= 0){ my $restcount = scalar(@{ $change[$rest]}); if($restcount + 1 < $count){ $denom = $coin; $count = $restcount + 1; } } } my $bestchange = [@{ $change[$q-$denom] }, $denom]; push @change, $bestchange; } for(my $q=1; $q <= $upper; $q++){ print "$q: "; print join(', ', @{ $change[$q] }); print "\n"; } }Addendum. Here is the version that collects all solutions. This is only interesting for small values since the greedy type behavior dominates with larger values.
#! /usr/bin/perl -w # MAIN: { my @coins = (1, 6, 10, 19); my $upper = shift || 42; my @change = ([[]]); for(my $q=1; $q <= $upper; $q++){ my ($count, $denom) = ($q+1, []); foreach my $coin (@coins){ my $rest = $q-$coin; if($rest >= 0){ my $restcount = scalar(@{ $change[$rest]->[0]}); if($restcount + 1 < $count){ $denom = [$coin]; $count = $restcount + 1; } elsif($restcount + 1 == $count){ push @$denom, $coin; } } } my $bestchange = []; foreach my $dn (@$denom){ foreach my $ch (@{ $change[$q-$dn] }){ push @$bestchange, [ @$ch, $dn ] if scalar(@$ch) == 0 || $ch->[-1] <= $dn; } } push @change, $bestchange; } for(my $q=1; $q <= $upper; $q++){ print "$q: "; my @sols = map { "[" . join(', ', @$_) . "]" } @{ $change[$q] }; print join(', ', @sols); print "\n"; } }This is the table that was computed.