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
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.
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.
A good integer is exactly three consecutive matching digits.
-
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:{
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.
-
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:{
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
posted at: 14:51 by: Adam Russell | path: /perl | permanent link to this entry