perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 312 - Task 1: Minimum Time

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-312/#TASK1
 3 #
 4 # Task 1: Minimum Time
 5 # ====================
 6 #
 7 # You are given a typewriter with lowercase english letters a to z arranged in
 8 # a circle.
 9 #
10 # Typing a character takes 1 sec. You can move pointer one character clockwise
11 # or anti-clockwise.
12 #
13 # The pointer initially points at a.
14 #
15 # Write a script to return minimum time it takes to print the given string.
16 #
17 ## Example 1
18 ##
19 ## Input: $str = "abc"
20 ## Output: 5
21 ##
22 ## The pointer is at 'a' initially.
23 ## 1 sec - type the letter 'a'
24 ## 1 sec - move pointer clockwise to 'b'
25 ## 1 sec - type the letter 'b'
26 ## 1 sec - move pointer clockwise to 'c'
27 ## 1 sec - type the letter 'c'
28 #
29 ## Example 2
30 ##
31 ## Input: $str = "bza"
32 ## Output: 7
33 ##
34 ## The pointer is at 'a' initially.
35 ## 1 sec - move pointer clockwise to 'b'
36 ## 1 sec - type the letter 'b'
37 ## 1 sec - move pointer anti-clockwise to 'a'
38 ## 1 sec - move pointer anti-clockwise to 'z'
39 ## 1 sec - type the letter 'z'
40 ## 1 sec - move pointer clockwise to 'a'
41 ## 1 sec - type the letter 'a'
42 #
43 ## Example 3
44 ##
45 ## Input: $str = "zjpc"
46 ## Output: 34
47 #
48 ############################################################
49 ##
50 ## discussion
51 ##
52 ############################################################
53 #
54 # Let's enumerate the characters on the circle with 0 for a
55 # up to 25 for z. The shortes way to another character is at
56 # most 13 steps, so we can calculate the difference from one
57 # character to the next: If that is bigger than 13, we should
58 # have walked in the opposite direction, which takes (26-steps)
59 # steps to reach the character. So for each character, we need
60 # to calculate the steps to walk and the extra second to print,
61 # of course tracking the new position after each step.
62 #
63 
64 use v5.36;
65 
66 minimum_time("abc");
67 minimum_time("bza");
68 minimum_time("zjpc");
69 
70 sub minimum_time($str) {
71    say "Input: \"$str\"";
72    my @chars = split //,$str;
73    my $ptr = 0;
74    my $output = 0;
75    foreach my $char (@chars) {
76       my $this = ord($char) - 97;
77       my $diff = abs($ptr - $this);
78       $ptr = $this;
79       if($diff > 13) {
80          $diff = 26 - $diff;
81       }
82       $output += $diff; # how many steps to go
83       $output++; # printing the character
84    }
85    say "Output: $output";
86 }
87