javascript - 比较多个点之间的距离

标签 javascript arrays iterator pythagorean

我正在尝试应用毕达哥拉斯定理来查找点数组之间的距离,因为我迭代数组,然后吐出 n 个最近的点。我很困惑如何获得 d: 迭代点和下一个点之间的距离,以与迭代点和之后的下一个 +1 点的距离进行比较,依此类推。我从我的一系列观点开始:

 var points = [
   { id: 1, x: 0.0, y: 0.0 },
   { id: 2, x: 10.1, y: -10.1 },
   { id: 3, x: -12.2, y: 12.2 },
   { id: 4, x: 38.3, y: 38.3 },
   { id: 5, x: 79.0, y: 179.0 },
 ];

然后我想迭代它们,并使用毕达哥拉斯定理为其与其他点之间的距离的每个点创建一个新数组:

points.forEach((item) => {
  var newArray = [item];
  var pt = null;
  var d = null;
  for (var i = 0; i < points.length; i = i + 1) {
      //compare this point with all of the other points 
      for (var j = i + 1; j < points.length; j = j + 1) {
          //compute distance 
          var curr = Math.sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2));
      //get the distance between each point and push to a new array  
          if (d === null || curr < d) {                 
            o = points.id[i];     
            pt = points.id[j];
            d = curr; 
          }
       }
     }    
  newArray.push = {
   "id": o,
   "pt": pt,
   "d": d
  };
  console.log(newArray);
});

似乎我这里的某些逻辑区域不正确,并且每当我尝试变化时,我都会不断收到随机无法读取未定义的属性'0'错误。对我做错了什么有什么建议吗?

最佳答案

您目前正在对每个项目进行三次迭代:您有一个forEach,其中有一个嵌套的for和另一个嵌套的for 。您还尝试对 points[i][0]points[j][0] 等进行数学计算,但这些不存在 - points例如,[j] 是具有 xy 属性的对象,而不是具有数字索引的数组。

如果给每个单独的点一个变量,并使用求幂运算符,就会更清楚:

var points = [
  { id: 1, x: 0.0, y: 0.0 },
  { id: 2, x: 10.1, y: -10.1 },
  { id: 3, x: -12.2, y: 12.2 },
  { id: 4, x: 38.3, y: 38.3 },
  { id: 5, x: 79.0, y: 179.0 },
];

const pointPairs = [];
for (let i = 0; i < points.length; i = i + 1) {
  const p1 = points[i];
  for (let j = i + 1; j < points.length; j = j + 1) {
    const p2 = points[j];
    const distance = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
    pointPairs.push({ p1: p1.id, p2: p2.id, distance });
  }
}
pointPairs.sort((a, b) => a.distance - b.distance);
console.log(pointPairs.slice(0, 5));

或者,如果您使用数组方法,它会更干净:

var points = [
  { id: 1, x: 0.0, y: 0.0 },
  { id: 2, x: 10.1, y: -10.1 },
  { id: 3, x: -12.2, y: 12.2 },
  { id: 4, x: 38.3, y: 38.3 },
  { id: 5, x: 79.0, y: 179.0 },
];

const pointPairs = [];
points.forEach((p1, i) => {
  points.slice(i + 1).forEach(p2 => {
    const distance = Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
    pointPairs.push({ p1: p1.id, p2: p2.id, distance });
  });
});
pointPairs.sort((a, b) => a.distance - b.distance);
console.log(pointPairs.slice(0, 5));

关于javascript - 比较多个点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882413/

相关文章:

c - 在 C 中使用快速排序反向排序(降序)?

Javascript函数参数作为数组

python - 压缩迭代器和计数迭代器的乘积

c++ - 不匹配运算符!=

javascript - 使用jquery将输入字段附加到DOM时如何在输入字段上添加值

javascript - Javascript 中的自动执行函数用于分析实现

c++ - 结构数组加倍算法 C++

c++ - 如何使用迭代器在 C++ 中的递归函数中传递值?

javascript - 使用 jQuery 遍历列表

javascript - 为表格中的多个单元格创建边框