合并2组间隔,同时将每个间隔从set1约束到set2的边界

时间:2018-01-06 18:13:41

标签: algorithm intervals overlap

这是一张说明我的意思的图片:

enter image description here

基本上我想将set1合并到set2中,但是不允许存在set1的每个间隔,除非它包含在set2的间隔范围内。

非常感谢任何建议!

PS:我的下一个任务是弄清楚如何将 n 数量的* set1 * s(即可能相互重叠的绿色层)合并到一个具有相同规则的set2中。 ..但我先从这开始!

2 个答案:

答案 0 :(得分:0)

  1. 将set2中的所有间隔添加到结果中。
  2. 将set1中的所有间隔添加到结果中,如果它们不完全适合set2的间隔,则“剪切”或完全删除它们。
  3. 合并结果集中的所有重叠间隔。
  4. 为了有效地实现第二步,您可以使用第一个坐标对set2中的间隔进行排序,并使用二进制搜索。第3步https://www.geeksforgeeks.org/merging-intervals/

答案 1 :(得分:0)

以下是JavaScript中这种合并的算法 - 它应该很容易在其他编程语言中重现:

function merge(segments1, segments2) {
    const result = [];
    let i = -1, start1 = -Infinity, end1 = -Infinity, 
        j = -1, start2 = -Infinity; end2 = -Infinity;
    while (i < segments1.length || j < segments2.length) {
        if (end1 <= start2) { // get next from segments1
            i++;
            start1 = i < segments1.length ? segments1[i][0] : Infinity;
            end1 = i < segments1.length ? segments1[i][1] : Infinity;
        } else if (end2 <= start1) { // flush and get next from segments2
            if (start2 < end2) result.push([start2, end2]);
            j++;
            start2 = j < segments2.length ? segments2[j][0] : Infinity;
            end2 = j < segments2.length ? segments2[j][1] : Infinity;
        } else { // overlap
            if (start2 < start1) {
                result.push([start2, start1]);
                start2 = start1;
            }
            start1 = Math.min(end2, end1);
            result.push([start2, start1]);
            start2 = start1;
        }
    }
    return result;
}

// Sample input
const segments1 = [[6, 7], [8, 11], [12, 14], [15, 18], [19, 20], [22, 23], 
                   [25, 26], [27, 28], [30, 31], [33, 35]],
      segments2 = [[6, 10], [11, 14], [16, 17], [18, 21], [22, 24], [24, 26],
                   [27, 28], [29, 31], [33, 34], [35, 36]];
// Merge and output
const result = merge(segments1, segments2);
console.log(JSON.stringify(result));

要合并多组线段,您只需调用上述函数:

merged = merge(green1, grey)
merged = merge(green2, merged)
merged = merge(green3, merged)
// ... etc