Search code examples
javajava-8localtime

Generate random time within a range of two times with condition


I'm trying to generate 10 random times within a range of two times, and there is a condition that the times generated cannot have less than 30 minutes between them. So, if i Start at 10:00am and end at 05:00pm, the times between these must be a least 30 minutes between them.

I already can get the random times, but don't know how to put the condition there, any ideas?

public LocalTime between(LocalTime startTime, LocalTime endTime) {
    int startSeconds = startTime.toSecondOfDay();
    int endSeconds = endTime.toSecondOfDay();
    int randomTime = ThreadLocalRandom
      .current()
      .nextInt(startSeconds, endSeconds);

    return LocalTime.ofSecondOfDay(randomTime);
}

i put this in a for loop to get 10 of them


Solution

  • For a good random distribution: Out of the 7 hours between your start of 10:00 and your end of 17:00 (on a 24 hour clock, “military hours”), 4 hours 30 minutes are already reserved for your minimal gaps (9 gaps @ 30 minutes minimum). So subtract 4:30 from 7, this gives 2 hours 30 minutes of freedom.

    1. Generate 10 random times within 2 hours 30 minutes, for example the way you already do.
    2. Sort them chronologically.
    3. Add 0 minutes to the first time, 30 minutes to the next, 1 hour to the third, etc. So you will be adding 4 hours 30 minutes to the last time. This will make sure that the gaps become at least 30 minutes each and that the last time is still within the 17:00 end time.