【问题标题】:How to intersect two arrays of ranges?如何相交两个范围数组?
【发布时间】:2018-09-02 09:05:30
【问题描述】:

范围 是两个整数的数组:startend(例如 [40, 42])。

有两个范围数组(已排序),我想找到计算它们交集的最佳方法(这将导致另一个范围数组):

A = [[1, 3], [7, 9], [12, 18]]
B = [[2, 3], [4,5], [6,8], [13, 14], [16, 17]]

路口:

[[2, 3], [7, 8], [13, 14], [16, 17]]

什么是最佳算法?


天真的方法是检查每个与所有其他的,但这显然不是最佳的。

我在 VBA 中发现了一个类似的问题:Intersection of two arrays of ranges

【问题讨论】:

  • 你如何得到那些 A、B 和交集数组? ??????
  • 所有范围都排序且不同吗?数组 1 可以是 [[4, 6], [1,2]] 吗?或[[1, 5], [4,6]]?
  • 假设数组已排序,这似乎相当简单。我错过了什么吗?
  • @PraveenKumar:输入数组就是:输入,给程序。交集也就是:范围集的交集,出现在AB 的范围中的值。
  • @LioraHaydont 不,那不可能。它们已经标准化。第一个是[[1, 2], [4, 6]],第二个是[[1, 6]]

标签: javascript arrays algorithm range


【解决方案1】:

由于输入数组已排序,因此计算起来应该相当简单。我假设任何一个输入数组中的范围都不会相互交叉(否则,“已排序”将是模棱两可的)。考虑每个数组的一个范围(由“当前范围”索引ab 定义)。有几种情况(“完全重叠”以外的每种情况都有一个镜像,其中AB是相反的):

没有交叉点:

A[a]: |------|
B[b]:          |---|

由于数组已排序,A[a] 不能与B 中的任何内容相交,因此可以跳过(递增a)。

部分重叠(B[b] 超出A[a]):

A[a]: |-------|
B[b]:      |-------|

在这种情况下,将交集添加到输出中,然后增加 a,因为 A[a] 不能与 B 中的任何其他内容相交。

遏制(可能是同时结束):

A[a]: |------|
B[b]:   |--|

再次将交集添加到输出中,这次增加b。请注意,进一步的轻微优化是如果A[a]B[b] 以相同的值结束,那么您也可以增加b,因为B[b] 也不能与A 中的任何其他内容相交。 (两端重合的情况可以归为部分重叠的情况。这种情况可以称为“严格遏制”。)

完全重叠:

A[a]: |------|
B[b]: |------|

将交集添加到输出并增加ab(两个范围都不能与另一个数组中的任何其他内容相交)。

继续迭代上面的代码,直到 ab 跑出对应数组的末尾,然后你就完成了。

将上面的内容翻译成代码应该是琐碎的

编辑:要备份最后一句话(好吧,这不是微不足道的),这是我上面的代码版本。由于所有情况,这有点乏味,但每个分支都非常简单。

const A = [[1, 3], [7, 9], [12, 18]];
const B = [[2, 3], [4, 5], [6, 8], [13, 14], [16, 17]];

const merged = [];

var i_a = 0,
    i_b = 0;

while (i_a < A.length && i_b < B.length) {
  const a = A[i_a];
  const b = B[i_b];

  if (a[0] < b[0]) {
    // a leads b
    if (a[1] >= b[1]) {
      // b contained in a
      merged.push([b[0], b[1]]);
      i_b++;
      if (a[1] === b[1]) {
        // a and b end together
        i_a++;
      }
    } else if (a[1] >= b[0]) {
      // overlap
      merged.push([b[0], a[1]]);
      i_a++;
    } else {
      // no overlap
      i_a++;
    }
  } else if (a[0] === b[0]) {
    // a and b start together
    if (a[1] > b[1]) {
      // b contained in a
      merged.push([a[0], b[1]]);
      i_b++;
    } else if (a[1] === b[1]) {
      // full overlap
      merged.push([a[0], a[1]]);
      i_a++;
      i_b++;
    } else /* a[1] < b[1] */ {
      // a contained in b
      merged.push([a[0], a[1]]);
      i_a++;
    }
  } else /* a[0] > b[0] */ {
    // b leads a
    if (b[1] >= a[1]) {
      // containment: a in b
      merged.push([a[0], b[1]]);
      i_a++;
      if (b[1] === a[1]) {
        // a and b end together
        i_b++;
      }
    } else if (b[1] >= a[0]) {
      // overlap
      merged.push([a[0], b[1]]);
      i_b++
    } else {
      // no overlap
      i_b++;
    }
  }
}
console.log(JSON.stringify(merged));

您要求优化算法。我相信我的非常接近最佳状态。它与两个数组中的范围数在线性时间内运行,因为每次迭代完成至少一个范围(有时是两个)的处理。它需要常量内存加上构建结果所需的内存。

我应该注意,与CertainPerformance 的答案(在我写这篇文章时在这里发布的唯一其他答案)不同,我的代码适用于任何类型的数字范围数据,而不仅仅是整数。 (如果您正在混合数字和数字的字符串表示形式,您可能希望将上面的 === 替换为 ==)。特定性能的算法将范围扁平化为跨越范围的连续整数数组。如果整数的总数是 n,那么他的算法在 O(n2) 时间和 O(n) 空间中运行。 (因此,例如,如果其中一个范围是 [1, 50000],则需要存储 50,000 个数字的内存,并且时间与它的平方成正比。)

【讨论】:

    【解决方案2】:

    非常简单,只需编写大量代码。将 ab 展平为单个元素而不是范围,找到它们的交点,然后再次将其转回范围数组。

    const a = [[1, 3], [7, 9], [12, 18]];
    const b = [[2, 3], [4,5], [6,8], [13, 14], [16, 17]];
    const rangeToArr = ([start, end]) => Array.from({ length: end - start + 1 }, (_, i) => start + i);
    const flat = inputArr => inputArr.reduce((arr, elm) => arr.concat(...elm), []);
    const aRange = flat(a.map(rangeToArr));
    const bRange = flat(b.map(rangeToArr));
    const intersection = aRange.filter(num => bRange.includes(num));
    console.log(intersection);
    
    
    // Have the intersection of elements
    // now we have to turn the intersection back into an array of ranges again:
    const { partialIntersectionRange, thisRangeStarted, lastNum }
    = intersection.reduce(({ partialIntersectionRange, thisRangeStarted, lastNum }, num) => {
      // Initial iteration only: populate with initial values
      if (typeof thisRangeStarted !== 'number') {
        return { partialIntersectionRange, thisRangeStarted: num, lastNum: num };
      }
      // If this element is a continuation of the range from the last element
      // then just increment lastNum:
      if (lastNum + 1 === num) {
        return { partialIntersectionRange, thisRangeStarted, lastNum: num };
      }
      // This element is not a continuation of the previous range
      // so make a range out of [thisRangeStarted, lastNum] and push it to the range array
      // (in case thisRangeStarted === lastNum, only push a single value)
      if (thisRangeStarted !== lastNum) partialIntersectionRange.push([thisRangeStarted, lastNum]);
      else partialIntersectionRange.push([thisRangeStarted]);
      return { partialIntersectionRange, thisRangeStarted: num, lastNum: num };
    }, { partialIntersectionRange: [] });
    if (thisRangeStarted !== lastNum) partialIntersectionRange.push([thisRangeStarted, lastNum]);
    else partialIntersectionRange.push([thisRangeStarted]);
    
    console.log(JSON.stringify(partialIntersectionRange));

    困难不在于交集逻辑,而在于将其格式化为所需的方式。

    【讨论】:

    • 您能添加一些 cmets 来说明您的代码在做什么吗?这样的块很难读
    • 如果范围包含大量数字(例如,[5000030, 1470000250]),这将非常低效。另外,因为它依赖于includes,所以这看起来像是一个 O(n^2) 算法,其中 n 是所有范围所跨越的整数总数,而不是范围的数量。
    【解决方案3】:

    @Ted Hopp 提出的想法可以用更少的代码来实现,如下所示:

    var A = [[1, 3], [7, 9], [12, 18]];
    var B = [[2, 3], [4, 5], [6, 8], [13, 14], [16, 17]];
    
    var result = [];
    var ai = 0, alength = A.length, ax, ay;
    var bi = 0, blength = B.length, bx, by;
    while (ai < alength && bi < blength) {
      ax = A[ai][0];
      ay = A[ai][1];
      bx = B[bi][0];
      by = B[bi][1];
      if (ay < bx) {
        // a ends before b
        ai++;
      } else if (by < ax) {
        // b ends before a
        bi++;
      } else {
        // a overlaps b
        result.push([ax > bx ? ax : bx, ay < by ? ay : by]);
        // the smaller range is considered processed
        if (ay < by) {
          ai++;
        } else {
          bi++;
        }
      }
    }
    console.log(result);

    下面是大数组的综合测试:

    var A = [];
    var B = [];
    var R = [];
    (function(rangeArray1, rangeArray2, bruteForceResult) {
      // create random, non-overlapping, sorted ranges
      var i, n, x, y;
      for (i = 0, n = 0; i < 1000; i++) {
        x = n += Math.floor(Math.random() * 100) + 1;
        y = n += Math.floor(Math.random() * 100);
        rangeArray1.push([x, y]);
      }
      for (i = 0, n = 0; i < 1000; i++) {
        x = n += Math.floor(Math.random() * 100) + 1;
        y = n += Math.floor(Math.random() * 100);
        rangeArray2.push([x, y]);
      }
      // calculate intersections using brute force
      rangeArray1.forEach(function(a) {
        rangeArray2.forEach(function(b) {
          if (b[1] >= a[0] && a[1] >= b[0]) {
            bruteForceResult.push([Math.max(a[0], b[0]), Math.min(a[1], b[1])]);
          }
        });
      });
    })(A, B, R);
    
    var result = [];
    var ai = 0, alength = A.length, ax, ay;
    var bi = 0, blength = B.length, bx, by;
    while (ai < alength && bi < blength) {
      ax = A[ai][0];
      ay = A[ai][1];
      bx = B[bi][0];
      by = B[bi][1];
      if (ay < bx) {
        // a ends before b
        ai++;
      } else if (by < ax) {
        // b ends before a
        bi++;
      } else {
        // a overlaps b
        result.push([ax > bx ? ax : bx, ay < by ? ay : by]);
        // the smaller range is considered processed
        if (ay < by) {
          ai++;
        } else {
          bi++;
        }
      }
    }
    console.log(JSON.stringify(R) === JSON.stringify(result) ? "test passed" : "test failed");

    【讨论】:

    • 我喜欢这个解决方案。它展示了一点点创造力可以做些什么来简化簿记问题。
    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多