如何找到最接近原点的坐标? [英] How to find the coordinate that is closest to the point of origin?

查看:244
本文介绍了如何找到最接近原点的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于按多个值对javascript数组进行排序的问题,但没有一个答案可以解决我的问题。



我有一个如下的坐标数组:

  x | y 
--------
10 20
12 18
20 30
5 40
100 2

如何获得最接近原点的坐标?



  Math.sqrt(Math.pow (x,2)+ Math.pow(y,2)); 

取最低的结果






  var points = [
{x:10,y:20},
{x:12,y:18 },
{x:20,y:30},
{x:5,y:40},
{x:100,y:2}
];

函数d(点){
返回Math.pow(point.x,2)+ Math.pow(point.y,2);

$ b $ var nearest = points.slice(1).reduce(function(min,p){
if(d(p) return min;
},{point:points [0],d:d(points [0])})。point;

最接近;
// {x:12,y:18}

您会注意到我们在这里跳过 Math.sqrt 步骤。正如Mark Setchell指出的那样,计算平方根是一种最低公分母操作;我们仍然可以通过获取最小的 x ^ 2 + y ^ 2 值来确定最接近的点。


I know there are many many questions about sorting javascript arrays by multiple values, but none of the answers solved my problem.

I have an array of coordinates like:

x  |  y
--------
10    20
12    18
20    30
5     40
100   2

How can I get the coordinate that is closest to the point of origin?

解决方案

Calculate the distance of each point using

Math.sqrt( Math.pow(x, 2) + Math.pow(y, 2) );

Take the result that's the lowest


var points = [
  {x: 10, y: 20},
  {x: 12, y: 18},
  {x: 20, y: 30},
  {x: 5, y: 40},
  {x: 100, y: 2}
];

function d(point) {
  return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}

var closest = points.slice(1).reduce(function(min, p) {
  if (d(p) < min.d) min.point = p;
  return min;
}, {point: points[0], d:d(points[0])}).point;

closest;
// {x: 12, y:18}

You'll notice that we're skipping the Math.sqrt step here. As Mark Setchell points out, calculating the square root is a sort of "lowest common denominator" operation; We can still determine the closest point by getting the smallest x^2 + y^2 value.

这篇关于如何找到最接近原点的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆