More generally, if you want to find out how many ways one can break n into chunks of size m1,...,mk, then the following command will print them out:% perl make_change.pl 100 50 25 10 5 1
% perl make_change.pl n m1 ... mk
Update: Spurred by Roy Johnson's reply++ I tightened my version slightly to take care of edge cases in a more natural way, and explicitly list the 0 coefficients. Originally I thought I liked the looks of the "zero-less" output better, but on a second thought I realized that a version of the core function that returns all the coefficients is more generally useful; the output can be easily tweaked by the calling code. The current version lists all the coefficients, one for each coin.
Keyword: partitions.
use strict; use warnings; sub make_change { my $amount = shift; return $amount ? () : [] unless @_; my $coin = pop; my $n_coins = 0; my $base = 0; my @ways; while ( $base <= $amount ) { push @ways, map [ @$_, [ $n_coins, $coin ] ], make_change( $amount - $base, @_ ); $n_coins++; $base += $coin; } return @ways; } sub print_way { my $way = shift; print join ' + ', map "$_->[ 0 ] x $_->[ 1 ]", @$way; print $/; } print_way( $_ ) for make_change( @ARGV );
In reply to How many ways to make change? by tlm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |