Give 3 intervals (a,b) , (c,d) , (e,f), what is the fastest way to detect (i.e. have a yes/no answer) if exists a value t that is at the same time a<=t<b AND c<=t<d AND e<=t<f ?
Is it also possible to compute the range of t that satisfies this condition, min(t),max(t)
?
Moreover, is it possible to do the same without any hypotesis about the order? (i.e. it could be also b<a
or a<b
)
I've found a well known solution for two segments but for three is not trivial.
Any js or python example code is welcome.
EDIT: corrected condition requirements
Python solution for any number of intervals regardless of order of the numbers in the interval. It'll either return True, min t value, max t value
or False, t value, t value
.
def in_interval(intervals):
if len(intervals) == 0:
return False, None, None
min_t = min(intervals[0])
max_t = max(intervals[0])
for interval in intervals[1:]:
min_t = max(min_t, min(interval))
max_t = min(max_t, max(interval))
if min_t > max_t:
return False, None, None
else:
return True, min_t, max_t
Test run:
>>> intervals = [(6,1),(2,20),(8,7)]
>>> in_interval(intervals)
(False, 1, 1)
>>> intervals = [(6,1),(2,20),(4,9)]
>>> in_interval(intervals)
(True, 4, 6)