在'圆形'数组中查找下一个位置

问题描述 投票:3回答:2

我有一个由SW编号的8个罗盘点阵列,从顺时针方向到S:

2 3 4
1   5
0 7 6

我想计算从一个点到另一个点的最短路线是顺时针(+1)还是逆时针(-1)。例如。从7到5将是-1,从7到0将是+ 1。

我想这个简单的问题,但今天我的大脑已经冻结了。

我最接近的是if abs(start - end) < 4, -1, 1,但如果开始是3则不起作用。

有一个类似的问题here,接受的答案是使用modulo,但没有解释如何。我没有成功地抛出各种计算。

c# arrays unity3d math unity5
2个回答
8
投票

而不是使用abs,添加8(条目数),然后采用modulo 8,如下所示:

enum Direction {
     None, Clockwise, Counterclockwise
}

public static Direction GetDirection(int a, int b) {
    if (a == b) {
        return Direction.None;
    }
    return (a-b+8)%8 > 4 ? Direction.Clockwise : Direction.Counterclockwise;
}

添加8使差异非负; modulo-8将它带入0 ... 7范围。

请注意,当步数为4时,无论你走哪条都没关系,所以程序更喜欢逆时针方向。您可以使用>=代替>来更改它。


0
投票

试试这个

int start=3;
int end=6;

var temp = start-end;
temp= temp < 0 ? temp + 7 : temp;

var result = temp < 4 ? -1 : 1;
© www.soinside.com 2019 - 2024. All rights reserved.