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

"ch-1.pl" Defined by 1.

"ch-2.pl" Defined by 5.

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.

"ch-1.pl" 1


preamble 2
twice appearance 3
main 4

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.

preamble 2 ⟩≡


use v5.38;

Fragment referenced in 1, 5.

twice appearance 3 ⟩≡


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 4 ⟩≡


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.

"ch-2.pl" 5


preamble 2
count asterisks 6
main 7

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.

count asterisks 6 ⟩≡


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 7 ⟩≡


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

The Weekly Challenge 280
Generated Code

posted at: 16:57 by: Adam Russell | path: /perl | permanent link to this entry