Completing the time and
levelling the letters
Weekly challenge 194 — 7 December 2022
Week 194: 7 Dec 2022
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.
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
There are six cases to consider:
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 '?'.
#!/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]; }
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