Peter’s blog ✴ Week 282 ✴ 12 August 2024
THE WEEKLY CHALLENGE
Integggers and 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.
Example 1 Input: $str = 'pPeERrLl' Output: 3 p -> P : 0 key change P -> e : 1 key change e -> E : 0 key change E -> R : 1 key change R -> r : 0 key change r -> L : 1 key change L -> l : 0 key change Example 2 Input: $str = 'rRr' Output: 0 Example 3 Input: $str = 'GoO' Output: 1
As in task 1, I could not see an obvious way to do this with a single regular expression, but this time, lower-casing the string and then comparing successive pairs of characters is relatively easy.
But I'm sure the RE experts will have found a better way.
Plenty to discuss about the issues faced with regex when using Perl and in the end the work around. Well done and keep it up.
This review may cover either or both challenges for this week.
I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-08-12 use utf8; # Week 282 - task 2 - Changing keys use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; changing_keys('aaabbbcCc'); changing_keys('abbbbb'); changing_keys('aaaaab'); changing_keys('abcde'); changing_keys('aAaAaAa'); changing_keys('Committee'); sub changing_keys { my ($str, $c, $count); # initialise $str = shift; say qq[\nInput: \@str = '$str']; # count key changes $str = lc($str); $count = 0; for $c (0 .. length($str) - 2) { $count ++ if substr($str, $c, 1) ne substr($str, $c + 1, 1); } say qq[Output: $count]; }
9 lines of code
Input: @str = 'aaabbbcCc' Output: 2 Input: @str = 'abbbbb' Output: 1 Input: @str = 'aaaaab' Output: 1 Input: @str = 'abcde' Output: 4 Input: @str = 'aAaAaAa' Output: 0 Input: @str = 'Committee' Output: 5
Any content of this website which has been created by Peter Campbell Smith is in the public domain