Monday, August 21, 2023

TWC231

 Challenge Link

Task1

We are asked to find the min and max elements of the array and then return those elements which are not equal to them. If the array length is less than 3 items we simply return -1 since there cannot be any other elements than that of min and max:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min max);

sub min_max
{
  my ($arr) = @_;
  return "-1\n" if @$arr < 3;
  my ($min,$max) = (min(@$arr),max(@$arr));
  sprintf "(%s)\n", join ',', grep{$_ != $min && $_ != $max} @$arr;
}

print min_max([3,2,1,4]);
print min_max([3,1]);
print min_max([2,1,3]);

Task2

The age is in the 4th position from the end of the string so we use substr to extract that and count how many of them are greater than or equal to 60:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/bin/env perl
use strict;
use warnings;

sub senior_citizens
{
  scalar grep{substr($_,-4,2) >= 60} @{$_[0]};
}

printf "%d\n",senior_citizens(["7868190130M7522",
			       "5303914400F9211",
			       "9273338290F4010"]);
printf "%d\n",senior_citizens(["1313579440F2036",
			       "2921522980M5644"]);

No comments:

Post a Comment