Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Random Change for a Dollar

by fredopalus (Friar)
on May 19, 2003 at 13:38 UTC ( [id://259143]=CUFP: print w/replies, xml ) Need Help??

This little program prints out a random combination of coins that make up a dollar.

use warnings; use strict; my @coins = ( {counter => 0, value => 25, name => "quarter"}, {counter => 0, value => 5, name => "nickel" }, {counter => 0, value => 10, name => "dime" }, {counter => 0, value => 1, name => "penny" } ); my $dollar = 100; my $totalval= 0; while ($totalval<100) { my $rnum = rand @coins; my $temp=$coins[$rnum]{value}+$totalval; if ($temp<=100) { $totalval += $coins[$rnum]{value}; $coins[$rnum]{counter}++; } else { ;; } } print "Change for a Dollar\n"; for(my $i=0; $i<=3; $i++) { print $coins[$i]{counter}, " ", $coins[$i]{name}, "(s)\n"; }

Update: This, BTW, is the first time I've submitted any kind of code.

Replies are listed 'Best First'.
Re: Random Change for a Dollar
by halley (Prior) on May 19, 2003 at 14:08 UTC

    A couple minor comments.

    First, separate the dynamic data from the static data. You have a nice little structure to define the coins, but you also store the counters in that same structure. This means you have to create or clear that definition table before every transaction. Keep them separate.

    Second, you're "humanizing" the output with names like quarter and nickel. So finish the job and get rid of that canned mechanical "penny(s)" wording, and don't mention the coins that are not counted. (Not tested.)

    foreach (@coins) { next if not $_->{counter}; my $name = (1==$_->{counter})? $_->{name} : ($_->{plural} || $_->{name}.'s'); print $_->{counter}, " ", $name, "\n"; }
    Threading it into a sentence instead of a columnar list is left as an exercise.

    --
    [ e d @ h a l l e y . c c ]

Re: Random Change for a Dollar
by TVSET (Chaplain) on May 19, 2003 at 17:31 UTC
    I think you did mean $dollar in all those places, where you have a 100. Actually, I am surprised that warnings didn't warn you about having a variable used in only one place. :)

    Leonid Mamtchenkov aka TVSET

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://259143]
Approved by sschneid
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-24 23:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found