开发者

Getting closest coordinates closest to point in array

I have one point (hereafter referred to as the original point) on a grid, say for example, [3, 3].

I also have a set of points that are in the same horizontal and vertical lines as the original point, say, [[3,1],[3,2],[3,4],[7,3],[8,3]].

I want some function that will return an array of at most four points: the points closest to the original point in each direction (i.e. left, right, above, below). With the example above, it would return,

[开发者_Python百科[3,2],[3,4],[7,3]]

because [3,2] is the closest point on the left, [3,4] is the closest point on the right, [7,3] is the closest point above, and there are no points below. (Order of direction is not important.)

Is there an elegant and reasonably concise way to do this, using Javascript/JQuery?


I don't know JavaScript, but the following algorithm would be very simple, if you can formulate it with JavaScript.

Let (X0, Y0) be the original point.

Iterate through the array, [(X1, Y1), ..., (XN, YN)], and keep account of the minimum values of

R = Xi - X0 > 0

and

L = X0 - Xi > 0

as you proceed. At the end of the iteration these values give you the closest points, i.e., X0 + R and X0 - L.

Do a similar iteration on the vertical line of points.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜