Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
You're looking for the Greedy Algorithm. It's basically the reverse from your approach: you start out with the highest denomination, then decrease that and spread the difference among the lower denominations.

Here's one link: http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Greedy/greedyIntro.htm

I dug up my solution to problem 31 on Project Euler.

#!/usr/bin/perl use List::Util qw/ sum /; @w = ( 1, 2, 5, 10, 20, 50, 100 ); $S = 100; $found = 0; @c = ( 0, 0, 0, 0, 0, 0, 1 ); partition( $S, @c ); print "$/Total found: $found$/"; sub partition { my ( $s, @c ) = @_; while(1) { # exact change $found++ if $s - amount( \@c, \@w ) == 0; # last match return if $c[0] == $s; # decrement first non-zero my $i = 0; $i++ while $c[$i] == 0; $i == 0 ? $c[0] = 0 : $c[$i]--; @c[ 0 .. $i - 1 ] = (0) x $i; # and redistribute difference for my $j ( reverse 0 .. $i - 1 ) { my $Dj = $s - amount( \@c, \@w ); $c[$j] = int( $Dj / $w[$j] ); } } } sub amount { my ( $x, $y ) = @_; return sum map { $x->[$_] * $y->[$_] } 0 .. $#$x; }

It could use some refactoring, but I was in a hurry and I didn't write it for public consumption ;)

Update: Oh right, yes, output... I get Total found: 4563.


In reply to Re: puzzle: how many ways to make $100 by rhesa
in thread puzzle: how many ways to make $100 by davidj

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2021-12-02 06:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (17 votes). Check out past polls.

    Notices?