I need to check if times A cross with times B using integers and a 24hour clock. Times that are the same don't count as crossing, but meeting.
For example: 16, 20 and 14, 18 (startA, endA and startB and endB) would return true as these times do cross, however, 14, 16 and 16, 20 meet but don't cross so they would return false. Any other combination that does not cross would return false.
Assuming that the times don't go past midnight I can just do this:
static boolean Cross(int startPeriod1, int endPeriod1, int startPeriod2, int endPeriod2) {
return startPeriod1 < endPeriod2 && endPeriod1 > startPeriod2;
}
However, to include times that do go past midnight (e.g 16, 2 and 14, 2 which would return true) I used this solution:
static boolean timesCrossLate(int startPeriod1, int endPeriod1, int startPeriod2, int endPeriod2) {
List<Integer> rangePeriod1;
List<Integer> rangePeriod2;
if (startPeriod1 > endPeriod1) {
List<Integer> rangeStartPeriod1 = IntStream.range(startPeriod1 + 1, 25).boxed().collect(Collectors.toList());
List<Integer> rangeEndPeriod1 = IntStream.range(0, endPeriod1).boxed().collect(Collectors.toList());
rangePeriod1 = Stream.concat(rangeStartPeriod1.stream(), rangeEndPeriod1.stream()).collect(Collectors.toList());
}
else {
rangePeriod1 = IntStream.range(startPeriod1 + 1, endPeriod1).boxed().collect(Collectors.toList());
}
if (startPeriod2 > endPeriod2) {
List<Integer> rangeStartPeriod2 = IntStream.range(startPeriod2 + 1, 25).boxed().collect(Collectors.toList());
List<Integer> rangeEndPeriod2 = IntStream.range(0, endPeriod2).boxed().collect(Collectors.toList());
rangePeriod2 = Stream.concat(rangeStartPeriod2.stream(), rangeEndPeriod2.stream()).collect(Collectors.toList());
}
else {
rangePeriod2 = IntStream.range(startPeriod2 + 1, endPeriod2).boxed().collect(Collectors.toList());
}
if (!Collections.disjoint(rangePeriod1, rangePeriod2)) {
return true;
}
else {
return false;
}
}
Here I make a list of the range of times and compare the two lists to see if any elements are shared, I of course don't include the start and end numbers as that would meant that the numbers meet and not cross.
I wanted to know if there is a better/ cleaner way of doing this (apart from making the list creation part into a separate method).
Thanks :)
timesCrossLate(20, 6, 2, 8)
return true or false, and why? \$\endgroup\$