Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing where the overlap is

If you have two pairs of values, start and end- how do you compute where their overlap is?

I.e if the pairs of start and end values are

[10, 20], [15, 20]

In this case compute_overlap((15,20),(10,20)) should return (15,20) because that is where the overlap is.

What is the best way to do this?

like image 598
The Unfun Cat Avatar asked Jul 30 '26 18:07

The Unfun Cat


1 Answers

If your intervals are a, b and c, d, i.e.

(a, b), (c, d) = [10, 20], [15, 20]

then the overlapping interval is

x, y = max(a, c), min(b, d)
if x > y:  # no overlap
    x, y = None, None

and the amount of overlap is y - x or y - x + 1, depending on whether your intervals are closed or half-closed (assuming integers here).

like image 80
Fred Foo Avatar answered Aug 01 '26 08:08

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!