Robbie Hatley's Solutions To The Weekly Challenge #231
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:
This week (2023-08-20 through 2023-08-26) is weekly challenge #230.
Task 1 is as follows:
Task 1: Min Max Submitted by: Mohammad S Anwar You are given an array of distinct integers. Write a script to find all elements which are neither minimum nor maximum. Return -1 if you can’t. Example 1: Input: @ints = (3, 2, 1, 4) Output: (3, 2) (The minimum is 1 and maximum is 4 in the given array. So (3, 2) are the elements which are neither min nor max.) Example 2: Input: @ints = (3, 1) Output: -1 (With only two distinct elements, each element is either min or max.) Example 3: Input: @ints = (2, 1, 3) Output: (2) (The minimum is 1 and maximum is 3 in the given array. So the only element that's neither min nor max is 2.)
I suppose I could use CPAN, but I feel like rolling my own tonight. Since the elements were specified to be "distinct", I'll start by sorting the array:
my @sorted = sort {$a<=>$b} @array;
Then the first element will be min and the last element will be max:
my $min = shift @sorted; my $max = pop @sorted;
Then just store the middle elements in an array:
my @middle; map {push @middle, $_ if $_ != $min && $_ != $max} @ints;
The script I came up with is this:
Robbie Hatley's Solution to The Weekly Challenge 231-1
Task 2 is as follows:
Task 2: Senior Citizens Submitted by: Mohammad S Anwar You are given a list of passenger details in the form “9999999999A1122”, where 9 denotes the phone number, A the sex, 1 the age, and 2 the seat number. Write a script to return the count of all senior citizens (persons with age >= 60). Example 1: Input: @list = ("7868190130M7522","5303914400F9211","9273338290F4010") Ouput: 2 (The age of the passengers in the given list are 75, 92 and 40, so we have only 2 senior citizens.) Example 2: Input: @list = ("1313579440F2036","2921522980M5644") Ouput: 0 (All passengers have age < 60.)
My approach to solving this was, for each "detail", increment a counter each time an age 60+ is seen, being careful to strip any leading 0 from the age (else octal!!!):
my $senior_count = 0; map {++$senior_count if (0 + ((substr $_, 11, 2) =~ s/^0//r)) >= 60} @$aref;
Here's the script I wrote:
Robbie Hatley's Solution to The Weekly Challenge 231-2
That's it for 231; see you on 232!
Comments
Post a Comment