【问题标题】:index of closest points between two sorted arrays of coordinates两个排序的坐标数组之间最近点的索引
【发布时间】:2015-10-06 22:46:48
【问题描述】:

我正在处理 javascript 中的优化问题。

我有两个数组:

dataset1 = [[x1,y1],[x2,y2],...,[xn,yn]]

dataset2 = [[z1,w1],[z2,w2],...,[zm,wm]]

dataset1 和dataset2 表示单调函数

x1 < x2 < ... < xn     (x coordinate)

z1 < z2 < ... < zm     (x coordinate)

和

y1 < y2 < ... < yn     (y coordinate)

w1 > w2 > ... > wm     (y coordinate)

因此,两个数据集的第一个坐标总是增加 dataset1 的第二个坐标总是增加,dataset2 的第二个坐标总是减少。

我正在寻找一种快速的二进制迭代算法来找到两个最接近的坐标对(两个单调函数的交点)。

有人知道怎么做吗?

【问题讨论】:

    标签: javascript arrays indexing closest sorted


    【解决方案1】:

    据我了解,您有两个单调函数,一个向右增加,一个向右减少。

    您的数组是已排序的点,因此每个点都从最差的x 坐标开始。

    你可以做的是将第一个数组的每个点与第二个数组的每个点进行比较,然后像这样存储一个对象:

    //point
    {
        pointIncreasing: [xj, yj],
        pointDecreasing: [zi, wi],
        distance : //distance between the points
    }
    

    然后计算你检查的距离:

    • 两者是否共享相同的x或y坐标,此时距离为Math.abs(xj-zi)或Math.abs(yj-wi)。

    • 如果他们不共享 x 或 y 坐标,您可以使用毕达哥拉斯定理找到距离为 d = Math.sqrt(Math.pow(Math.abs(xj-zi),2) + Math.pow(Math.abs(yj-wi),2))

    所以最后你会得到一个这样的函数:

    var results = [];
     function populateResults(fun1, fun2){
        for (var j = 0; j < fun1.length; j++){
            for (var i = 0; i< fun2.length; i++){
                var temp = {
                    pointI : fun1[j],
                    pointD : fun2[i],
                    d : null
                }
                // do as said before, add some ifs, calculate distance
                // and do a temp.d = calculatedDistance
    
                // and add an if calculatedDistance == 0, to stop the
                // loop, because you got your intersection
                results.push(temp);
            }
        }
    
        results.sort(function(a, b){return (a.d - b.d);});
        // to sort your results array, not sure of order though...
    }
    

    然后你只需要采取results[0] 并且你有两个最近的点,或者如果distance == 0 是交叉点。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 2018-06-16
      • 2019-09-09
      • 2012-06-02
      • 1970-01-01
      • 2020-03-04
      • 2017-05-29
      • 2012-06-04
      • 2012-03-01
      相关资源
      最近更新 更多