Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading