Idrees Samim
Idrees Samim

Reputation: 463

index of closest points between two sorted arrays of coordinates

I am working on an optimization problem in javascript.

I have two arrays:

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

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

dataset1 and dataset2 represent monotonic functions

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

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

and

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

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

Therefore, the first coordinate of both datasets always increases The second coordinate of dataset1 always increases and the second coordinate of dataset2 always decreases.

I am looking for a fast binary iterative algorithm to find the two closest pair of coordinates (intersection of the two monotonic functions).

Does anyone know how to do it?

Upvotes: 3

Views: 412

Answers (1)

Jo Colina
Jo Colina

Reputation: 1924

as I understand, you have two monotonic functions, one that increases to the right, and one that decreases to the right.

Your arrays are sorted points, thus beginning at the most inferior x coordinate for each one.

What you could do is compare each point of the first array to each point of the second array, and store an object like so:

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

And then to calculate the distance you check:

  • Whether the two share the same x or y coordinate, in which case the distance is Math.abs(xj-zi) or Math.abs(yj-wi).

  • If they don't share an x or y coordinate you can use the theorem of Pythagoras to find the distance as d = Math.sqrt(Math.pow(Math.abs(xj-zi),2) + Math.pow(Math.abs(yj-wi),2))

So at the end you would get a function like so:

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...
}

And then you just need to take results[0] and you've got your two closest points, or intersection if distance == 0.

Hope this helps!

Upvotes: 2

Related Questions