DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

Efficient PHP Function for Counting Valid Time Formats with '?' Placeholder (Turing code challenge)

Are you in need of a versatile PHP function to count the number of valid time formats with a '?' placeholder? Look no further! In this post, we'll explore a well-optimized PHP function, countValidTimeFormats, that efficiently generates and validates time formats.

<?php
function countValidTimeFormats($s) {
    $count = 0;
    $splited  = explode(':', $s);
    $range = stripos($splited[0], '?') !== false ? range(0, 24) : range(0,59);
    foreach($range as $num){

      $formattedTime = stripos($splited[0], '?') !== false ? 
              str_replace('?', $num, $splited[0]).':'.$splited[1] : 
              $splited[0] .':'.str_replace('?', $num, $splited[1]);
        // Validate the formatted time
        if (isValidTime($formattedTime)) {
            $count++;
        }
    }

    return $count;
}

function isValidTime($time) {
    $pattern = '/^(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/';
    return preg_match($pattern, $time);
}

// Example usage
echo countValidTimeFormats("?4:00"); // Output: 2
echo countValidTimeFormats("20:1?"); // Output: 10
?>
Enter fullscreen mode Exit fullscreen mode

countValidTimeFormats Function:
Input Splitting: $splited = explode(':', $s); - Splits the input string into an array using the colon (':') as the delimiter. This separates the hours and minutes.
Determine Range: $range = stripos($splited[0], '?') !== false ? range(0, 24) : range(0, 59); - Determines the range of values based on the presence of '?' in the hour component. If '?' exists, the range is set from 0 to 24 (hours); otherwise, it is set from 0 to 59 (minutes).
Generate and Validate Formats: The foreach loop iterates through the specified range. It generates a formatted time string by replacing the '?' with the current value in either the hour or minute component based on the determined range. The formatted time is then validated using the isValidTime function.
Count Valid Formats: If the generated time format is valid, $count++ increments the count.
Return Count: The function returns the final count of valid time formats.
isValidTime Function:
Time Format Validation: $pattern = '/^(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/'; - Defines a regular expression pattern for validating the 24-hour time format (hh:mm).

Validation Check: return preg_match($pattern, $time); - Uses preg_match to check if the provided time string matches the specified pattern.

In summary

The code efficiently generates and validates time formats based on the presence of '?' in the input string. It handles both hour and minute placeholders, ensuring adherence to the 24-hour time format. The provided example usage demonstrates how the function can be applied to count valid time formats for different input strings.

Top comments (0)