Change Counting Problem - Feedback Requested

There's a common programming challenge where you write a program to take a dollar amount from the user, and then return the simplest way to create that amount with only coins (using the fewest coins possible). I took a crack at this a while back, and I would like to know if there are ways it could be improved or if you would have done it differently.


use strict;
use warnings;
 
print "Input a dollar amount: ";
my $amount = readline STDIN;
chomp ($amount);

$amount = $amount * 100;
$amount = sprintf($amount);

my $quarter = 25;
my $dime = 10;
my $nickel = 5;
my $penny = 1;

my $qnum = $amount / $quarter;
$qnum = int($qnum);
my $remainder = $amount % $quarter;

my $dnum = $remainder / $dime;
$dnum = int($dnum);
$remainder = $remainder % $dime;

my $nnum = $remainder / $nickel;
$nnum = int($nnum);
$remainder = $remainder % $nickel;

my $pnum = $remainder / $penny;
$pnum = int($pnum);
$remainder = $remainder % $penny;

unless ($qnum == 0) {
print "$qnum quarters\n";
}

unless ($dnum == 0) {
print "$dnum dimes\n";
}

unless ($nnum == 0) {
print "$nnum nickels\n";
}

unless ($pnum == 0) {
print "$pnum pennies\n";
}

There is no commenting because the code is from the site that I put tutorials on. If you want my explanation on why I'm doing something, you can see the tutorial. I won't be rewriting this tutorial, though if I learn any new skills from your comments, I may indeed include them in future tutorials.

Thanks in advance for your time and energy.

5 Comments

Looks like a lot of copy-paste there. How about this?

It's worth noting that this solution also makes using a different currency very easy - just populate the hash accordingly. For example, using British coinage.

I wish there was a way to edit ones comments here. That second link should have been http://gist.github.com/8176950.

Put 1¢ to 24¢ in an array:

my @small = (
  "",
  "1 penny\n",
  "2 pennies\n",
  "3 pennies\n",
  "4 pennies\n",
  "1 nickel\n",
  "1 nickel\n1 penny\n",
  "1 nickel\n2 pennies\n",
  "1 nickel\n3 pennies\n",
  "1 nickel\n4 pennies\n",
  "1 dime\n",
  "1 dime\n1 penny\n",
  "1 dime\n2 pennies\n",
  "1 dime\n3 pennies\n",
  "1 dime\n4 pennies\n",
  "1 dime\n1 nickel\n",
  "1 dime\n1 nickel\n1 penny\n",
  "1 dime\n1 nickel\n2 pennies\n",
  "1 dime\n1 nickel\n3 pennies\n",
  "1 dime\n1 nickel\n4 pennies\n",
  "2 dimes\n",
  "2 dimes\n1 penny\n",
  "2 dimes\n2 pennies\n",
  "2 dimes\n3 pennies\n",
  "2 dimes\n4 pennies\n",
);

for ( 1 .. 10 ){
my $amt = int( rand( 1000 ));
printf "%.2f\n", $amt / 100;

my $q = int( $amt / 25 );
my $r = $amt % 25;

if( $q == 1 ){
print "1 quarter\n";
}elsif( $q > 1 ){
print "$q quarters\n";
}
print "$small[ $r ]\n";
}

One more gem from Toby. Thanks Toby.

Leave a comment

About Chris K

user-pic I'm a student teaching himself Perl and want to learn more.