计算连续整数序列的交集?

时间:2016-01-06 20:16:37

标签: javascript numerical-methods

在JavaScript中,计算连续整数序列交集的正确方法是什么?

例如A = (1...10)B = (7...20)以及C = (3..5) - 结果我想知道A与B相交,但B与C不相交。

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

假设AB& C是数组,然后您可以使用您的边界值组合对象,如下所示:

bounds_a = {
    start: Math.min.apply(null, A),
    end: Math.max.apply(null, A),

}

你甚至可以为这个课提供帮助:

var Bounds = function(src){
    this.min = Math.min.apply(null, src)
    this.max = Math.max.apply(null, src)
    this.size = Math.abs(max - min + 1) //+1 since we're dealing with integers and need to account for the lowest value
}

Bounds.prototype.intersects = function(target){
    rangeMin = Math.min(this.min, target.min)
    rangeMax = Math.max(this.max, target.max)

    range = Math.abs(rangeMax - rangeMin)
    width = this.size + target.size

    return range < width
}

可以在此处找到有关重叠逻辑的更好解释 - What's the most efficient way to test two integer ranges for overlap?

测试:

var A = <array 1...10>
var B = <array 7...20>
var C = <array 3...5>

var a = new Bounds(A) //min: 1, max: 10, size: 10
var b = new Bounds(B) //min: 7, max: 20, size: 14
var c = new Bounds(C) //min: 3, max: 5, size: 3

a.intersects(b) //true
b.intersects(c) //false
a.intersects(c) //true

答案 1 :(得分:0)

var intersect = function(a, b) {
    // Assume a & b are sorted

  var c = []

  for(var i = 0; i < a.length; i++) {
        for(var j = 0; j < b.length; j++) {
        if(a[i] == b[j]) {
          c.push(a[i]);
        }
      }
    }
    return c;
  }

A = []
B = []

A.push(1, 3, 5, 2, 4, 7)
B.push(2,4,8,10,7,5,1)
A.sort()
B.sort()

alert(intersect(A,B))

答案 2 :(得分:0)

最好我可以告诉你只想知道它们是否相交。

is_intersecting = (minA <= maxB && maxA >= minB);

根据评论,您可以将a.start替换为minA,将a.end替换为maxA,然后执行操作。可能更好地将其包装在一个函数中。

答案 3 :(得分:0)

如果有一个结果,请使用返回新范围对象的类和方法。此解决方案适用于任何浮动或间隙。

&#13;
&#13;
/**
 * $request is an array of data
 */
public function getGridValue(Request $request)
{
    // returns "Foo"
    $object = $request->query('object');

    // returns "Bar"
    $value = $request->query('value');

    // returns array of entire input query...can now use $query['value'], etc. to access data
    $query = $request->all();

    // Or to keep business logic out of controller, I use like:
    $n = new MyClass($request->all());
    $n->doSomething();
    $n->etc();
}
&#13;
&#13;
&#13;