RabbitFarm
2024-08-04
Asterisks Appear Twice
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
File Index
Part 1: Twice Appearance
You are given a string, $str, containing lowercase English letters only. Write a script to print the first letter that appears twice.
The complete solution is contained in one file that has a simple structure.
For this problem we do not need to include very much. We’re just specifying to use the current version of Perl, for all the latest features in the language. This fragment is also used in Part 2.
-
sub twice_appearance{
my($s) =
@_;
my
@a = ();
do{
$a[ord($_)]++;
return $_ if $a[ord($_)] == 2;
} for split //, $s;
return undef;
}
◇
-
Fragment referenced in 1.
Now all we need are a few lines of code for running some tests.
-
MAIN:{
say twice_appearance q/acbddbca/;
say twice_appearance q/abccd/;
say twice_appearance q/abcdabbb/;
}
◇
-
Fragment referenced in 1.
Sample Run
$ perl perl/ch-1.pl d c a
Part 2: Count Asterisks
You are given a string, $str, where every two consecutive vertical bars are grouped into a pair. Write a script to return the number of asterisks, *, excluding any between each pair of vertical bars.
This is our principal function. As can be seen, it’s very short! The logic here is simple: peel off pairs and use a regex to find the asterisks.
-
sub count_asterisks{
my($s) = shift;
my $score = 0;
my
@asterisks = ();
my
@s = split /\|/, $s;
{
my $x = shift
@s;
my $y = shift
@s;
my
@a = $x =~ m/(\*)/g if $x;
push
@asterisks,
@a if
@a > 0;
redo if
@s >= 1;
}
return 0 +
@asterisks;
}
◇
-
Fragment referenced in 5.
Finally, here’s a few tests to confirm everything is working right.
-
MAIN:{
say count_asterisks q/p|*e*rl|w**e|*ekly|/;
say count_asterisks q/perl/;
say count_asterisks q/th|ewe|e**|k|l***ych|alleng|e/;
}
◇
-
Fragment referenced in 5.
Sample Run
$ perl ch-2.pl 13 30 37
References
posted at: 16:57 by: Adam Russell | path: /perl | permanent link to this entry