Perl Weekly Challenge #236 - Lemonade Stand

Welcome back to another round of the weekly challenge, with just one solution this week. I'm setting up a lemonade stand and need to deal with change. Interestingly, I can only sell one juice per person, so I hope you're not super thirsty!

We can take $5, $10, and $20 bills, and we don't start with any change, so we need our previous customers to provide us with change for future customers. Let's find out if we can make change for a set of customers.

Here's the code:

#!/usr/bin/perl
use v5.36;
use List::Util 'any';

my %till;
my $failure;
foreach my $bill (@ARGV) {
    if(!any {$bill == $_} (5, 10, 20)) {
        say('At least one bill provided is not $5, $10, or $20.') and exit;
    }
    $till{$bill}++;
    if($bill == 20) {
        if($till{10} and $till{5}) {
            $till{10}--;
            $till{5}--;
        } elsif($till{5} >= 3) {
            $till{5} -= 3;
        } else {
            $failure = 'false';
            last;
        }
    } elsif($bill == 10) {
        if($till{5}) {
            $till{5}--;
        } else {
            $failure = 'false';
            last;
        }
    }
}
say(defined($failure) ? $failure : 'true');

It might be possible to make this cleaner, but this is what I came up with quickly, so here it is. Our cash drawer is represented by the hash %till, which contains our $5s, $10s, and $20s. We add each bill we get, then we need to make change (unless it's a 5). If we can't make change at any point, we set our failure flag and stop serving customers. We check for the ability to successfully make change depending on the bill we've been handed. For a 20, first we try to make change with a $10 and a $5, otherwise three $5s, and for a $10 we see if we have any $5s. That's all we have to do! It's a lot of code for a simple result.

Hope to see you all next week. Enjoy!

Leave a comment

About oldtechaa

user-pic Just getting back into Perl programming. I have a personal project, SeekMIDI, a small graphical MIDI sequencer.