圆形阵列中两个元素之间的最小距离

时间:2013-05-03 15:30:50

标签: javascript math

给定一个圆形数组,确定两个元素之间的最小距离的有效方法是什么?

例如从这里搬家

[0,0,0,0,0,1]

到这里

[1,0,0,0,0,0]

从这里搬出时,外边界更方便

[0,0,0,0,0,1]

到这里

[0,0,0,1,0,0]

内部更方便。

我最初的想法是:

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;
}

注意:rotate将圆形数组旋转一定数量的位置。

3 个答案:

答案 0 :(得分:7)

计算元素之间的绝对距离很有用:

var dist = Math.abs(targetLocation - sourceLocation);

然后你可以检查它是否大于或小于数组长度的一半。如果距离超过长度的一半,则更接近于环绕:

if (dist < rotatorElements["pos"].length / 2) {
  // move internally
} else {
  // wrap around
}

编辑:

我将代码粘贴在一起:

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);

输出:

wrap, direction = 1
internally, direction = -1

演示:http://jsfiddle.net/bUCmk/

答案 1 :(得分:3)

编辑:我想我在标题中回答了问题,但你想要的是一个方向而不是距离。然后:

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;
    }
}

答案 2 :(得分:0)

这里我的解决方案(在groovy中)为您提供方向和距离(如果输出为负,则逆时针移动):

def move(def start, def target, def length){
    def clockwise
    def counterclockwise
    if (start > target){
        clockwise = length - start + target
        counterclockwise = start - target
    } else {
        clockwise = target - start
        counterclockwise = length - target + start
    }
    if (counterclockwise < clockwise){
        return counterclockwise * -1
    }
    return clockwise
}

这是输出:

groovy:000> move(0,0,0)
===> 0
groovy:000> move(0,0,4)
===> 0
groovy:000> move(0,1,4)
===> 1
groovy:000> move(0,2,4)
===> 2
groovy:000> move(0,3,4)
===> -1
groovy:000> move(1,0,4)
===> -1
groovy:000> move(1,1,4)
===> 0
groovy:000> move(1,2,4)
===> 1
groovy:000> move(1,3,4)
===> 2
groovy:000> move(2,0,4)
===> 2
groovy:000> move(2,1,4)
===> -1
groovy:000> move(2,2,4)
===> 0
groovy:000> move(2,3,4)
===> 1
groovy:000> move(3,0,4)
===> 1
groovy:000> move(3,1,4)
===> 2
groovy:000> move(3,2,4)
===> -1
groovy:000> move(3,3,4)
===> 0