Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Here are two subs which solve the make change problem using regexes. First one is the greedy algorithm, second one is the best change. Both subs take as first argument the amount to make change for, then a list of denominations. First sub uses 'pure' regexes, second sub uses a code fragment.
sub greedy_change { my $change = shift; my @coins = sort {$b <=> $a} @_; my $re; $re .= sprintf '((?:%s)*)', '1' x $_ for @coins; if (my @chunks = ('1' x $change) =~ /$re/) { return map {length($chunks[$_])/$coins[$_]} 0 .. $#coins; } else { return; } } sub best_change { my $change = shift; my @coins = sort {$b <=> $a} @_; our $S = $change + 1; our @C = (); my $re; $re .= sprintf '((?:%s)*)', '1' x $_ for @coins; $re .= '$(?{my @c = map {length($$_)/$coins[$_-1]} 1 .. @coins; my $s = 0; $s += $_ for @c; if ($s < $S) {$S = $s; @C = @c}})'; $re .= '(?!)'; use re 'eval'; ('1' x $change) =~ /^$re/; @C; }

In reply to Re: The greedy change-making problem using regexes by Anonymous Monk
in thread The greedy change-making problem using regexes by blokhead

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 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?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (8)
As of 2024-04-19 12:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found