javaarrayscombinationsclockdigital

Java — How to find all valid combinations for a digital clock with hours, minutes and seconds?


I need to fill a String array in Java with all possible combinations for a digital clock (but only as HHMMSS instead of HH:MM:SS) like these:

000000 000001 010000 235903

Invalid ones would be:

240000 000160 006000

and so on.

Is there an easier way to do this than convert the numbers from 0 to 999.999 to properly formatted Strings (from 000000 to 999999) and remove all the invalid ones?

This kind of the nested loops solution I was trying to avoid:

String[] arr = new String[24 * 60 * 60];

int index = 0;

for (int hours = 0; hours < 24; hours++) {
    for (int minutes = 0; minutes < 60; minutes++) {
        for (int seconds = 0; seconds < 60; seconds++) {
            
            arr[index] = String.format("%02d%02d%02d", hours, minutes, seconds);
            index++;
        }
    }
}

Solution

  • Using java.time package:

    var formatter = DateTimeFormatter.ofPattern("HHmmss");
    var hms = new String[24 * 60 * 60];
    for (var i = 0; i < hms.length; i++) {
        hms[i] = formatter.format(LocalTime.ofSecondOfDay(i));
    }
    

    Three nested loops:

    var hms = new String[24 * 60 * 60];
    var index = 0;
    for (var h = 0; h < 24; h++) {
        for (var m = 0; m < 60; m++) {
            for (var s = 0; s < 60; s++) {
                hms[index++] = String.format("%02d%02d%02d", h, m, s);
            }
        }
    }
    

    Single loop, using format to format time in Milliseconds (not so sure if that is recommended):

    var hms = new String[24 * 60 * 60];
    for (var i = 0; i < hms.length; i++) {
        hms[i] = String.format("%TH%1$TM%1$TS", i * 1000L);
    }