Monday, August 14, 2023

TWC230

 Challenge Link

Task1

We are asked to break the numbers which are greater than 9 to their constituent digits and splice them into the array which can be simply done with a split on an empty string in Perl:

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

sub separate_digits
{
  map{split ''} @{$_[0]};
}

printf "(%s)\n", join ",", separate_digits([1,34,5,6]);
printf "(%s)\n", join ",", separate_digits([1,24,51,60]);

Task2

We are asked to count the words starting with a prefix, which can be done with the '^' symbol and the regexp's powerful mechanism. I've also used the quotemeta to escape magic characters so that the variable is correctly interpolated inside the regex pattern:

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

sub count_words
{
  scalar grep{/^\Q$_[1]/} @{$_[0]};
}

printf "%d\n",count_words([qw/pay attention practice attend/],'at');
printf "%d\n",count_words([qw/janet julia java javascript/],'ja');

No comments:

Post a Comment