Jump to content

Count the coins/0-1: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 22:
 
*  Show an example of coins you used to reach the given sum by giving the indices of coins you have taken.
 
=={{header|Perl}}==
<lang perl>#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Count_the_coins/0-1
use warnings;
 
countcoins( 6, [1, 2, 3, 4, 5] );
countcoins( 6, [1, 1, 2, 3, 3, 4, 5] );
#countcoins( 40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100] );
 
sub countcoins
{
my ($want, $coins) = @_;
print "\nsum $want coins @$coins\n";
count($want, [], 0, $coins);
}
 
sub count
{
my ($want, $used, $sum, $have) = @_;
if( $sum == $want ) { print "used @$used\n" }
elsif( $sum > $want or @$have == 0 ) {}
else
{
my ($thiscoin, @rest) = @$have;
count( $want, [@$used, $thiscoin], $sum + $thiscoin, \@rest);
count( $want, $used, $sum, \@rest);
}
}</lang>
Third case not shown because it's too large.
{{out}}
<pre>
sum 6 coins 1 2 3 4 5
used 1 2 3
used 1 5
used 2 4
 
sum 6 coins 1 1 2 3 3 4 5
used 1 1 4
used 1 2 3
used 1 2 3
used 1 5
used 1 2 3
used 1 2 3
used 1 5
used 2 4
used 3 3
</pre>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.