Algorithm for Intersection (or Merge) of Numerical Ranges

╄→гoц情女王★ 提交于 2019-12-12 03:54:02

问题


Let's say I have a list of ranges like this:

List A) 0 to 3, 9 to 14

List B) 1 to 4, 6 to 7, 14 to 16

List C) 15 (i.e., 15 to 15)

I'd like to get a merged list of these ranges where the result would look like this:

Merged Result List) 0 to 4, 6 to 7, 9 to 16

(notice that the result is a merging/intersection/union of Lists A, B, and C)

I'm sure there's an algorithm for this, but have no idea. Has anyone come across this before?

(pseudocode, or VB, would be great)

Adding a visual representation:


回答1:


Make array/list of pairs (Value, Flag = +1 for start or -1 for end of range)

Sort these pairs by Value (use Flag as secondary key in case of tie)

Make Counter = 0

Walk through sorted array, adding Flag to Counter

When Counter becomes non-zero, merged range begins.

When Counter becomes zero, merged range ends

P.S. If you want to merge "touching" intervals - account for Flag in comparator function during sorting when Value is the same - for example, (14;+1) before (14,-1)



来源:https://stackoverflow.com/questions/44932842/algorithm-for-intersection-or-merge-of-numerical-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!