早上好:)我正在C#上工作,我想写一个代码,可以计算从任何点到特定点的较少跳数,如图所示
click here to show the picture
我有从1到12的点,所以如果我想计算点12到1的较少跳数,它将是逆时针方向的1,而不是顺时针方向的11跳。另一个例子来澄清我的问题,如果我想计算从点11到点4的较少跳数,逆时针方向是5,而不是顺时针方向是6。注意:点数可能是奇数。我希望你能理解我的问题。
发布于 2016-04-19 15:06:55
尝试顺时针方向,逆时针方向,并采取最小
private static int Hops(int a, int b) {
return Math.Min((12 + a - b) % 12, (12 + b - a) % 12);
}测试:
// 5
Console.WriteLine(Hops(11, 4));
// 1
Console.WriteLine(Hops(12, 1));编辑:正如Matthew Watson在评论中提到的,你可能想知道它是顺时针还是逆时针
private static int ClockwiseHops(int a, int b) {
return (12 + b - a) % 12;
}
private static int AntiClockwiseHops(int a, int b) {
return (12 + a - b) % 12;
}
private static int Hops(int a, int b) {
return Math.Min(ClockwiseHops(a, b), AntiClockwiseHops(a, b));
}
private static String Solve(int a, int b) {
int hops = Hops(a, b);
if (hops == ClockwiseHops(a, b))
return String.Format("{0} -> {1} (clockwise) {2} hops", a, b, hops);
else
return String.Format("{1} -> {0} (anticlockwise) {2} hops", a, b, hops);
}测试:
// 12 -> 1 (clockwise) 1 hops
Console.WriteLine(Solve(12, 1));
// 11 -> 4 (clockwise) 5 hops
Console.WriteLine(Solve(11, 4));发布于 2016-04-19 15:10:23
你考虑过%模运算符吗?这将得到第一个数除以第二个数的余数。例如:
6 % 3 = 0 (3恰好是6的两倍,因此剩余为零)
10 % 4 = 2 (4进入10两次,余数为2)
因此,您需要尝试这两条路线,然后检查哪条路线更小。
所以试试吧:
int numberOfPositions = 12;
Math.Min ((numberOfPositions + b - a) % numberOfPositions, (numberOfPositions + a -b) % numberOfPositions);如果你想看看模数计算是如何工作的,这里有一个在线计算器:http://www.miniwebtool.com/modulo-calculator/
发布于 2016-04-19 15:17:41
有这么简单吗?
int NUM_OF_NODES = 12;
int numOfHops = NUM_OF_NODES;
int point1 = 11;
int point2 = 4;
int path1 = Math.Abs(point1 - point2);
int path2 = numOfHops - path1;
int result = path1 < path2 ? path1 : path2;
return result;对于简单函数
public int getLeastPath(int point1, int point2)
{
int path1 = Math.Abs(point1 - point2);
int path2 = NUM_OF_NODES - path1;
return path1 < path2 ? path1 : path2;}
https://stackoverflow.com/questions/36710748
复制相似问题