Peter’s blog ✴ Week 194 ✴ 7 December 2022

THE WEEKLY CHALLENGE
Completing the time and levelling the letters

The Perl Camel

Task 1

Digital clock

You are given time in the format hh:mm with one missing digit. Write a script to find the highest digit between 0-9 that makes it a valid time.

Examples


Example 1
Input: $time = '?5:00'
Output: 1
Since 05:00 and 15:00 are valid time and no other digits can fit in the missing place.

Example 2
Input: $time = '?3:00'
Output: 2

Example 3
Input: $time = '1?:00'
Output: 9

Example 4
Input: $time = '2?:00'
Output: 3

Example 5
Input: $time = '12:?5'
Output: 5

Example 6
Input: $time =  '12:5?'
Output: 9

Analysis

There are six cases to consider:

  1. The first digit is ? and the second is [0123] - the answer is 2
  2. The first digit is ? and the second is [456789] - the answer is 1
  3. The second digit is ? and the first is 1 - the answer is 9
  4. The second digit is ? and the first is 2 - the answer is 3
  5. The third digit is ? - the answer is 5
  6. The fourth digit is ? - the answer is 9

This is a rather messy set of conditions. The easiest - and perhaps clearest - way of performing the task is just a set of if ... elsif clauses using the above logic, and that's what I submitted. I used split to put the characters into in array to make my conditions easy to read - for example $chars[0] eq '?' - but it could equally be done using regular expressions - for example
$string =~ m|^...\?| is true if the 4th character, ie third digit, is '?'.

Perl Weekly’s review

from PW issue 594

Compact collection of various test cases. This makes the logic easy to follow. Keep it up great work.

Try it 

Try running the script with any input:



example: 2?:00

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-12-06
# PWC 194 task 1

use v5.28;
use utf8;
use warnings;

my (@tests, $test, @chars, $result);

@tests = ('?5:00', '?3:00', '1?:00', '2?:00', '12:?5', '12:5?');

# loop over tests
for $test (@tests) {
    @chars = split(//, $test);
    
    if ($chars[0] eq '?') {        # ?1:30 or ?5:30
        $result = $chars[1] > 3 ? '1' : '2';
        
    } elsif ($chars[1] eq '?') {   # 1?:30 or 2?:30
        $result = $chars[0] eq '2' ? '3' : '9';
        
    } elsif ($chars[3] eq '?') {   # 11:?0
        $result = '5';
        
    } elsif ($chars[4] eq '?') {   # 11:3?
        $result = '9';
        
    } else {
        $result = 'invalid';
    }
    say qq[\nInput:  $test\nOutput: $result];
}

18 lines of code

Output from script


Input:  ?5:00
Output: 1

Input:  ?3:00
Output: 2

Input:  1?:00
Output: 9

Input:  2?:00
Output: 3

Input:  12:?5
Output: 5

Input:  12:5?
Output: 9

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain