There are 292 ways to break a dollar using half-dollars, quarters, dimes, nickels, and cents. The following snippet lists them all. Use
% perl make_change.pl 100 50 25 10 5 1
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 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.