August 2023 Archives

Perl Weekly Challenge #231 - Not Going to Extremes but Accepting Senior Citizens

Hi everybody! In this week's weekly challenge, we're searching for anything but the minimum or maximum in a dataset, and searching for senior citizens on a plane.

Min And Max

This challenge is a very interesting one, because obviously the easiest solution in terms of development is to sort and filter the first and last element. However, that is O(n log n) and it's very little added complexity to do the O(n) solution with a single-pass filter.

my %hist;
$hist{$_} = 1 for @ARGV;

say "You didn't provide two or more arguments." and exit if scalar keys %hist < 2;
say "-1" and exit if scalar keys %hist == 2;

my ($max, $min);
for (keys %hist) {
    $max = $_ if (!defined($max) || $_ > $max);
    $min = $_ if (!defined($min) || $_ < $min);
}
for (keys %hist) {
    say $_ if $_ != $max and $_ != $min;
}

First we make a histogram hash where duplicates are filtered out. Using the histogram, we exit with a failure or -1 if there are 1 or 2 unique numbers left. As we scan the histogram keys we keep track of the minimum/maximum values, then one more pass to print all of them out.

Senior Citizens

Contrary to the typical pattern of the second challenge being harder, this one's incredibly simple. We're looking for any senior citizens in a dataset made up of "9999999999A1122”, where 9 denotes the phone number, A the sex, 1 the age and 2 the seat number.

The simplest way I can think of is substr():

my $count;
for (@ARGV) {$count++ if substr($_, 11, 2) >= 60}
say $count // 0;

That's it! We just count up every time substr() comes up with someone 60 or over. Then we print out the result.

That's it for this week! Hopefully I'll be back with another blog post next week.

Perl Weekly Challenge #230 - Turning Numbers into Characters and Words into Numbers

Hi everybody! I'm finally back with another PWC/TWC blog post for week 230.

Separate Digits

For the first challenge we want to split all the numbers in the array into single digits. Here's the code:

use v5.36;
my @nums;
push(@nums, split(//, $_)) for @ARGV;
say $_ for @nums;

It very simply splits anything in its arguments into individual characters and pushes them onto a new array.

Count Words

Our second challenge asks us to count the words that start with the given prefix. Here's a 4-liner (minus boilerplate) to help us out with this one:

use v5.36;
my $pattern = shift;
my $count;
for (@ARGV) {$count++ if $_ =~ /^$pattern/}
say $count // 0;

We take the pattern and then add to the count if our regex prefix matches the start of any of the strings in the arguments.

That's all for this week, two nice easy challenges! Hope I'll be able to post again next week maybe.

About oldtechaa

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