9

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

例如从这里搬家

[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将圆形阵列旋转定义的位置数。

4

3 回答 3

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/

于 2013-05-03T15:37:42.500 回答
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;
    }
}
于 2013-05-03T15:42:54.450 回答
0

这是我的解决方案(常规),它为您提供方向和距离(如果输出为负数,则逆时针移动):

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
于 2014-05-23T17:05:36.297 回答