Integggers and keys
Weekly challenge 282 — 12 August 2024
Week 282: 12 Aug 2024
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.
#!/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]; }
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