简体   繁体   中英

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 (ie left, right, above, below). With the example above, it would return,

[[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, ie, X0 + R and X0 - L .

Do a similar iteration on the vertical line of points.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM