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

Time:04-01

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("ddd", hours, minutes, seconds);
            index  ;
        }
    }
}

CodePudding user response:

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("ddd", 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);
}

CodePudding user response:

Nested loops

You know there are twenty-four hours, 0 through 23.

You know there are sixty minutes possible, 0 through 59.

And there are 60 seconds, if we ignore Leap Second, 0 through 59.

Do you can set up the nested for loops. Canonically, we often use these single characters as the names of the counter in each loop: i, j, and k. But in your case I world use names of hour, minute, second.

To most efficiently build up the text, use StringBuilder object.

I’m not show the actual code to preserve for you the joy of completing your own schoolwork assignment.

CodePudding user response:

No loops at all:

java.util.stream.LongStream.
           range(0, 24 * 60 * 60).
           mapToObj(x -> java.time.LocalTime.ofSecondOfDay(x)).
           collect(java.util.stream.Collectors.toList()).
           forEach(x -> System.out.println(x.format(java.time.format.DateTimeFormatter.ofPattern("HHmmss"))));
  • Related