RabbitFarm

2024-08-12

It’s Good To Change Keys

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: Good Integer

You are given a positive integer, $int, having 3 or more digits. Write a script to return the Good Integer in the given integer or -1 if none found.

The complete solution is contained in one file that has a simple structure.

"ch-1.pl" 1


preamble 2
good integer? if so, return it, else return -1 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.

A good integer is exactly three consecutive matching digits.

good integer? if so, return it, else return -1 3 ⟩≡


sub good_integer{
my($x) = @_;
return qq/$1$2/ if $x =~ m/([0-9])(\1{2,})/ &&
length qq/$1$2/ == 3;
return -1;
}

Fragment referenced in 1.

Now all we need are a few lines of code for running some tests.

main 4 ⟩≡


MAIN:{
say good_integer q/12344456/;
say good_integer q/1233334/;
say good_integer q/10020003/;
}

Fragment referenced in 1.

Sample Run
$ perl perl/ch-1.pl 
444 
-1 
000
    

Part 2: Changing Keys

You are given an alphabetic string, $str, as typed by user. Write a script to find the number of times user had to change the key to type the given string. Changing key is defined as using a key different from the last used key. The shift and caps lock keys won’t be counted.

"ch-2.pl" 5


preamble 2
count the number of key changes 6
main 7

count the number of key changes 6 ⟩≡


sub count_key_changes{
my($s) = @_;
my $count = 0;
my @s = split //, lc $s;
{
my $x = shift @s;
my $y = shift @s;
$count++ if $x && $y && $x ne $y;
unshift @s, $y if $y;
redo if @s;
}
return $count;
}

Fragment referenced in 5.

Finally, here’s a few tests to confirm everything is working right.

main 7 ⟩≡


MAIN:{
say count_key_changes(q/pPeERrLl/);
say count_key_changes(q/rRr/);
say count_key_changes(q/GoO/);
}

Fragment referenced in 5.

Sample Run
$ perl ch-2.pl 
3 
0 
1
    

References

The Weekly Challenge 282
Generated Code

posted at: 14:51 by: Adam Russell | path: /perl | permanent link to this entry