2011-09-18 24 views
0

给出下面的方向枚举:在数字键盘上的两个键之间寻找方向的算法?

typedef enum { 
    DirectionNorth = 0, 
    DirectionNorthEast, 
    DirectionEast, 
    DirectionSouthEast, 
    DirectionSouth, 
    DirectionSouthWest, 
    DirectionWest, 
    DirectionNorthWest 
} Direction; 

而且类似于数字小键盘数字矩阵:

7 8 9 
4 5 6 
1 2 3 

你怎么会写一个函数从矩阵返回相邻数字之间的方向是什么?你说:

1, 2 => DirectionEast 
2, 1 => DirectionWest 
4, 8 => DirectionNorthEast 
1, 7 => undef 

,如果你愿意,你可以改变枚举的数值。首选可读解决方案。 (不是家庭作业,只是我正在工作的应用程序的算法,我有一个工作版本,但我对更优雅的需求感兴趣。)

回答

3
int direction_code(int a, int b) 
{ 
    assert(a >= 1 && a <= 9 && b >= 1 && b <= 9); 
    int ax = (a - 1) % 3, ay = (a - 1)/3, 
     bx = (b - 1) % 3, by = (b - 1)/3, 
     deltax = bx - ax, deltay = by - ay; 
    if (abs(deltax) < 2 && abs(deltay) < 2) 
     return 1 + (deltay + 1)*3 + (deltax + 1); 
    return 5; 
} 

所得码是

1 south-west 
2 south 
3 south-east 
4 west 
5 invalid 
6 east 
7 north-west 
8 north 
9 north-east 
+0

很好的回答!我会添加一个结果,所以5成为无效。这样我就可以把结果看作是从数字小键盘中心的方向。 –

+0

@ K-ballo:好的建议,编辑。 – 6502

3

我将重新定义enum中的值,以便North,South东方和西方各有不同。

typedef enum { 
    undef = 0, 
    DirectionNorth = 1, 
    DirectionEast = 2, 
    DirectionSouth = 4, 
    DirectionWest = 8, 
    DirectionNorthEast = DirectionNorth | DirectionEast, 
    DirectionSouthEast = DirectionSouth | DirectionEast, 
    DirectionNorthWest = DirectionNorth | DirectionWest, 
    DirectionSouthWest = DirectionSouth | DirectionWest 
} Direction; 

有了这些新的价值观:

int ax = (a - 1) % 3, ay = (a - 1)/3; 
int bx = (b - 1) % 3, by = (b - 1)/3; 

int diffx = std::abs(ax - bx); 
int diffy = std::abs(ay - by); 

int result = undef; 
if(diffx <= 1 && diffy <= 1) 
{ 
    result |= (bx == ax - 1) ? DirectionWest : 0; 
    result |= (bx == ax + 1) ? DirectionEast : 0; 
    result |= (by == ay - 1) ? DirectionSouth : 0; 
    result |= (by == ay + 1) ? DirectionNorth : 0; 
} 
return static_cast<Direction>(result); 

更新:最后,我现在认为它是正确的。

+0

对于一个给定的'x',有多好,以至于设置了多个位,因为只有那些'y =='平等中的一个才是真的? –

+0

@Damien_The_Unbeliever:在那里,我这次做得对吗? –

+0

现在我相信了(一直在忙着发布一个带有更正的平等性的答案) –

0

利用该矩阵编号的下式成立: 1)的1的差(+已经或-ve)总是意味着方向是东或西。 2)相似,北方或南方方向相差3。 3)相差4东北或西南。 4)相差2北西或东南。