The weekly challenge 282 - Task 2: Changing Keys

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-282/#TASK2
 3 #
 4 # Task 2: Changing Keys
 5 # =====================
 6 #
 7 # You are given an alphabetic string, $str, as typed by user.
 8 #
 9 # Write a script to find the number of times user had to change the key to type
10 # the given string. Changing key is defined as using a key different from the
11 # last used key. The shift and caps lock keys won’t be counted.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = 'pPeERrLl'
16 ## Ouput: 3
17 ##
18 ## p -> P : 0 key change
19 ## P -> e : 1 key change
20 ## e -> E : 0 key change
21 ## E -> R : 1 key change
22 ## R -> r : 0 key change
23 ## r -> L : 1 key change
24 ## L -> l : 0 key change
25 #
26 ## Example 2
27 ##
28 ## Input: $str = 'rRr'
29 ## Ouput: 0
30 #
31 ## Example 3
32 ##
33 ## Input: $str = 'GoO'
34 ## Ouput: 1
35 #
36 ############################################################
37 ##
38 ## discussion
39 ##
40 ############################################################
41 #
42 # We lowercase the whole string first. Then we just need to count
43 # the number of changes that happen.
44 
45 use strict;
46 use warnings;
47 
48 changing_keys('pPeERrLl');
49 changing_keys('rRr');
50 changing_keys('GoO');
51 
52 sub changing_keys {
53    my $str = shift;
54    print "Input: '$str'\n";
55    $str = lc($str);
56    my $last = undef;
57    my $changes = 0;
58    foreach my $char (split //, $str) {
59       if(defined($last)) {
60          if($last ne $char) {
61             $changes++;
62             $last = $char;
63          }
64       } else {
65          $last = $char;
66       }
67    }
68    print "Output: $changes\n";
69 }