如何计算 'square' 距离,分 8 个方向
How to calculate 'square' distance, in steps in 8 directions
注意:我可能 google 这个问题,但我不知道使用正确的术语。
所以我在一个方形网格上工作,其中的棋子可以在 8 个方向(即水平、垂直或对角线)上移动,对于某些决策过程,我需要计算空间之间的“方形”距离。这是在这 8 个方向上到达那里所需的步数。它看起来像这样(为清楚起见添加了颜色。
到目前为止,我已经尝试计算方向
distance_between(source, target) {
var x_dist = Math.abs(source.x - target.x);
var y_dist = Math.abs(source.y - target.y);
return x_dist + y_dist;
}
这更像是一个菱形图案,从 4 个方向(水平或垂直)到达那里所需的步数。结果如下所示:
我觉得应该有一个简单的方法来计算平方距离,但是如果没有朝那个方向重复步骤,我不知道那会是什么。我怎样才能找到两个空间之间的平方距离?
知道这种距离叫什么也可能有用,所以我可以在这上面寻找几何资源。
您正在寻找的距离将是您当前函数中 x_dist
或 y_dist
中较大的一个。
function distance_between(source, target) {
var x_dist = Math.abs(source.x - target.x);
var y_dist = Math.abs(source.y - target.y);
return Math.max(x_dist, y_dist);
}
const
matrix = Array.from({ length: 7 }, (_, i) => Array.from({ length: 7 }, (_, j) => ({ x: j, y: i }))),
mapDistancesFrom = (source = { x: 0, y: 0 }) =>
matrix.map((row) => row.map((col) => distance_between(source, col)));
console.log('Matrix');
matrix.forEach(row => console.log(row.map(({ x, y }) => `(${x},${y})`).join(' ')));
console.log('\nDistances from (3,3)');
mapDistancesFrom({ x: 3, y: 3 }).forEach(row => console.log(row.join(' ')));
console.log('\nDistances from (2,2)');
mapDistancesFrom({ x: 2, y: 2 }).forEach(row => console.log(row.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
注意:我可能 google 这个问题,但我不知道使用正确的术语。
所以我在一个方形网格上工作,其中的棋子可以在 8 个方向(即水平、垂直或对角线)上移动,对于某些决策过程,我需要计算空间之间的“方形”距离。这是在这 8 个方向上到达那里所需的步数。它看起来像这样(为清楚起见添加了颜色。
到目前为止,我已经尝试计算方向
distance_between(source, target) {
var x_dist = Math.abs(source.x - target.x);
var y_dist = Math.abs(source.y - target.y);
return x_dist + y_dist;
}
这更像是一个菱形图案,从 4 个方向(水平或垂直)到达那里所需的步数。结果如下所示:
我觉得应该有一个简单的方法来计算平方距离,但是如果没有朝那个方向重复步骤,我不知道那会是什么。我怎样才能找到两个空间之间的平方距离?
知道这种距离叫什么也可能有用,所以我可以在这上面寻找几何资源。
您正在寻找的距离将是您当前函数中 x_dist
或 y_dist
中较大的一个。
function distance_between(source, target) {
var x_dist = Math.abs(source.x - target.x);
var y_dist = Math.abs(source.y - target.y);
return Math.max(x_dist, y_dist);
}
const
matrix = Array.from({ length: 7 }, (_, i) => Array.from({ length: 7 }, (_, j) => ({ x: j, y: i }))),
mapDistancesFrom = (source = { x: 0, y: 0 }) =>
matrix.map((row) => row.map((col) => distance_between(source, col)));
console.log('Matrix');
matrix.forEach(row => console.log(row.map(({ x, y }) => `(${x},${y})`).join(' ')));
console.log('\nDistances from (3,3)');
mapDistancesFrom({ x: 3, y: 3 }).forEach(row => console.log(row.join(' ')));
console.log('\nDistances from (2,2)');
mapDistancesFrom({ x: 2, y: 2 }).forEach(row => console.log(row.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }