How to get overlap range of two range

后端 未结 4 1550
眼角桃花
眼角桃花 2020-12-21 09:25

I have the following ranges in interval [1-15]

I want to find the overlap ranges between people 1 & 2.

Person1 [1, 3] [5, 10] Person2 [2, 4] [8, 15]

4条回答
  •  别那么骄傲
    2020-12-21 09:49

    Sort the starts and ends of the ranges.. keeping information alongside as to whether its a range-start or finish... for your example you'll get this:

    1 start
    2 start
    3 end
    4 end
    5 start
    8 start
    10 end
    15 end
    

    Now loop over these points and keep a counter.. +1 for a start -1 for an end. This counter is the number of overlapping segments at any time. If you want the boundaries you need to test each time you increase or decrease the counter. If you increase it from 1 to 2 this is a start of an overlapping range.. the end of the overlapping range will be when you decrease the counter from 2 to 1

    Martin

提交回复
热议问题