给定一个圆形阵列,确定两个元素之间的最小距离的有效方法是什么?
例如从这里搬家
[0,0,0,0,0,1]
Run Code Online (Sandbox Code Playgroud)
到这里
[1,0,0,0,0,0]
Run Code Online (Sandbox Code Playgroud)
从这里开始,从外边界更方便
[0,0,0,0,0,1]
Run Code Online (Sandbox Code Playgroud)
到这里
[0,0,0,1,0,0]
Run Code Online (Sandbox Code Playgroud)
内部更方便.
我最初的想法是这样的:
sourceLocation = rotatorElements["pos"].indexOf(1);
targetLocation = rotatorElements["pos"].rotate(delta).indexOf(1);
var D = Math.abs(targetLocation - sourceLocation);
var O = Math.abs(rotatorElements["pos"].length - D);
if ((D - O == 0)) direction = 1;
else {
if (D < O) direction = -1;
else direction = 1;
}
Run Code Online (Sandbox Code Playgroud)
注意:rotate将圆形阵列旋转定义的位置数.
计算元素之间的绝对距离很有用:
var dist = Math.abs(targetLocation - sourceLocation);
Run Code Online (Sandbox Code Playgroud)
然后你可以检查它是否大于或小于数组长度的一半.如果距离超过长度的一半,则更接近于环绕:
if (dist < rotatorElements["pos"].length / 2) {
// move internally
} else {
// wrap around
}
Run Code Online (Sandbox Code Playgroud)
我将代码粘贴在一起:
function move(sourceLocation, targetLocation, length) {
var dist = Math.abs(targetLocation - sourceLocation);
var direction = sourceLocation < targetLocation ? 1 : -1;
if (dist < length / 2) {
console.log('internally, direction =', direction);
} else {
console.log('wrap, direction =', -direction);
}
}
move(5, 0, 6);
move(5, 3, 6);
Run Code Online (Sandbox Code Playgroud)
输出:
wrap, direction = 1
internally, direction = -1
Run Code Online (Sandbox Code Playgroud)
编辑:我想我回答了标题中的问题,但你想要的是方向而不是距离。然后:
function getDirection(from, to, array) {
if (from === to) {
return 0;
}
var internal = (Math.max(from, to) - Math.min(from, to) < array.length/2) ? true : false;
if (internal && from < to
||
!internal && from > to
) {
return 1;
} else {
return -1;
}
}
Run Code Online (Sandbox Code Playgroud)