DEV Community

Simon Green
Simon Green

Posted on

Digital frequency

Weekly challenge 194

Challenge, My solutions

Task 1: Digital Clock

Task

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 valid time.

My solution

This is relatively straight forward. The following rules apply.

  • If the first digit is missing, it will be '2' if the second digit to 3 or less (being 20 to 23), otherwise it will be one (being 14 to 19).
  • If the second digit is missing it will be '3' if the first digit is 2, otherwise it will be one.
  • If the third digit is missing, the answer will be five (being 50 to 59).
  • If the last digit is missing, the answer will be nine (being 09, 19, ..., 59).

Examples

 ./ch-1.py ?5:00
1

$ ./ch-1.py ?3:00
2

$ ./ch-1.py 1?:00
9

$ ./ch-1.py 2?:00
3

$ ./ch-1.py 12:?5
5

$ ./ch-1.py 12:5?
9
Enter fullscreen mode Exit fullscreen mode

Task 2: Frequency Equalizer

Task

You are given a string made of alphabetic characters only, a-z.

Write a script to determine whether removing only one character can make the frequency of the remaining characters the same.

My solution

I am concerned that I have over-engineered this task. An easier option may have been to remove each digit one by one and see if the resulting string meets the criteria.

  1. The first step is to calculate the frequency of each letter. This is stored in the letter_freq dict (hash in Perl). The key is the letter, and the value is the number of occurrences of that letter.
  2. The next step is to calculate the frequency of frequencies. This is stored in the freq dict. The key is the frequency, and the value is the number of times that frequency occurs.
  3. We know that there will only be a possible solution is there are only 2 values in the freq dict.
  4. I then find the (numerically) minimum and maximum frequency value and store this as min_freq and max_freq respectively. The solution can only be found if one of the following is true:
    • The minimum frequency is 1 and it occurs once. Removing that letter means the remaining letters will all occur the same.
    • The difference between the minimum and maximum is 1, and the higher value occurs once. Remove the extra letter means all the letters will have the same frequency.
  5. Then as I am writing the blog post, I realized that there is another situation. If all letters only occur once, then removing any letter means the remaining characters also only appear once. It was at this point, I knew I probably have found the wrong technique for solving this challenge.

Examples

$ ./ch-2.py abbc
1

$ ./ch-2.py xyzyyxz
1

$ ./ch-2.py xzxz
0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)