我有一个由小立方体组成的大立方体。大立方体包括10个立方体宽,10个立方体的长度,10个立方体的高度。总共1000立方体。
我想确定哪个是最接近蓝色立方体的绿色立方体。
另一件重要的事情是,多维数据集的每一面都连接到对方(即第10行被认为在第1行旁边)。这是环绕效应。
例如,如果蓝色立方体在坐标9:8:8,绿色立方体在1:2:2,5:5:3和6:3:4,那么在1:2:2 :2处的绿色立方体应该被认为是最近的立方体。如果我的计算是正确的,那么它的距离应该是10,而另外两个人的距离是12。
如果没有多维数据集环绕(侧1与侧10连接),我就可以在JavaScript中得到以下内容:
let lowest = 1000;
let lowest_index = -1;
for (i = 0; i < green_cube.length; i++){
let x_offset = Math.abs(blue_cube.x - green_cube[i].x);
let y_offset = Math.abs(blue_cube.y - green_cube[i].y);
let z_offset = Math.abs(blue_cube.z - green_cube[i].z);
let distance = x_offset + y_offset + z_offset;
if (distance < lowest){
lowest = distance;
lowest_index = i;
}
}什么是正确的方式编码时,这一套生效?
更新
要弄清楚,距离必须是从A点到B点的立方体数的距离。距离必须只沿着X、Y和Z轴移动,因此对角线距离不能工作。我相信这在3D空间中被称为出租车距离。
发布于 2018-09-17 20:56:35
我相信这通常被称为“环绕”。
要考虑到你的距离测量,例如x维数,应该是:
let x_offset = Math.min((10 + blue.x - green[i].x) % 10, (10 + green[i].x - blue.x) % 10)x_offset将永远是积极的。
发布于 2018-09-17 20:57:42
这是一个让你保持头脑清醒的愚蠢伎俩。
设v是向量(5, 5, 5) - blue_cube。将v添加到每个立方体的位置,如果它脱离边缘,则加/减10。现在蓝色立方体在(5, 5, 5),到其他立方体的最短路径不再离开边缘。
在您的示例中,v = (5, 5, 5) - (9, 8, 8) = (-4, -3, -3)。第一个绿色立方体移动到(1, 2, 2) + (-4, -3, -3) = (-3, -1, -1) = (7, 9, 9),它的距离是10,第二个绿色立方体移动到(5, 5, 3) + (-4, -3, -3) = (1, 2, 0),它的距离是12,第三个绿色立方体移动到(6, 3, 4) + (-4, -3, -3) = (2, 0, 1),它的距离又是12,所以第一个绿色立方体确实是最近的。
发布于 2018-09-17 21:43:52
在这段代码中,我使用了三维两点的距离计算公式(参考文献)。

const calculateDistance3d = ({x: x1, y: y1, z: z1}, {x: x2, y: y2, z: z2}) => {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2));
}
const calculateLoopedDistance = (cubeA, cubeB) => {
return calculateDistance3d(cubeA, {
x: cubeA.x + 10 - Math.abs(cubeB.x - cubeA.x),
y: cubeA.y + 10 - Math.abs(cubeB.y - cubeA.y),
z: cubeA.z + 10 - Math.abs(cubeB.z - cubeA.z)
});
};
const getClosest = (green_cube, blue_cube) => {
let minDistance = 1000;
let closestIndex = 0;
blue_cube.forEach((cube, index) => {
const distance = calculateDistance3d(green_cube, cube);
const loopedDistance = calculateLoopedDistance(green_cube, cube);
if (distance < minDistance || loopedDistance < minDistance) {
minDistance = Math.min(distance, loopedDistance);
closestIndex = index;
}
});
return closestIndex;
}
console.log(getClosest({x: 9, y: 8, z: 8}, [
{x: 1, y: 2, z: 2},
{x: 5, y: 5, z: 3},
{x: 6, y: 3, z: 4}
]));
console.log(getClosest({x: 9, y: 8, z: 8}, [
{x: 5, y: 5, z: 3},
{x: 1, y: 2, z: 2},
{x: 6, y: 3, z: 4}
]));
在这个脚本的末尾,有两个包含多维数据集的日志。您可以在那里测试不同的数据。
更新/修正了calculateLoopedDistance()函数I,这是不正确的。
https://stackoverflow.com/questions/52375010
复制相似问题