找到数字键盘上两个键之间方向的算法?
给定以下方向枚举:
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
如果您愿意,您可以更改枚举的数值。首选可读的解决方案。 (不是作业,只是我正在开发的应用程序的算法。我有一个工作版本,但我对更优雅的方式感兴趣。)
Given the following direction enum:
typedef enum {
DirectionNorth = 0,
DirectionNorthEast,
DirectionEast,
DirectionSouthEast,
DirectionSouth,
DirectionSouthWest,
DirectionWest,
DirectionNorthWest
} Direction;
And number matrix similar to the numeric pad:
7 8 9
4 5 6
1 2 3
How would you write a function to return the direction between adjacent numbers from the matrix? Say:
1, 2 => DirectionEast
2, 1 => DirectionWest
4, 8 => DirectionNorthEast
1, 7 => undef
You may change the numeric values of the enum if you want to. Readable solutions preferred. (Not a homework, just an algorithm for an app I am working on. I have a working version, but I’m interested in more elegant takes.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
结果代码是
resulting codes are
我将重新定义枚举中的值,以便北、南、东和西各取不同的位。
有了这些新值:
更新:最后,我认为现在是正确的。
I would redefine the values in the enum so that North, South, East and West take a different bit each.
With those new values:
Update: Finally, I think its correct now.
对于这个数字矩阵,以下内容成立:
1) 差值 1(+ve 或 -ve)始终意味着方向是东或西。
2)相似,北或南方向相差3。
3) 东北或西南相差 4 度。
4) 西北或东南相差2。
With this matrix of numbers the following holds true:
1) a difference of 1 (+ve or -ve) always implies that the direction is either east or west.
2) similary, a difference of 3 for direction north or south.
3) a difference of 4 north east or south west.
4) a difference of 2 north west or south east.