<分区>
早上好 :) 我正在使用 C#,我想编写一个代码来计算从任意点到特定点的较少跳数,如图所示
click here to show the picture
我有从 1 到 12 的点,所以如果我想计算从点 12 到 1 的较少跳数,逆时针方向为 1,而不是顺时针方向为 11 跳。 另一个例子来澄清我的问题,如果我想计算从点 11 到 4 的较少跳数,逆时针方向为 5,而不是顺时针方向为 6 跳。注意:点数可能是奇数。 我希望你能理解我的问题..
标签 c#
<分区>
早上好 :) 我正在使用 C#,我想编写一个代码来计算从任意点到特定点的较少跳数,如图所示
click here to show the picture
我有从 1 到 12 的点,所以如果我想计算从点 12 到 1 的较少跳数,逆时针方向为 1,而不是顺时针方向为 11 跳。 另一个例子来澄清我的问题,如果我想计算从点 11 到 4 的较少跳数,逆时针方向为 5,而不是顺时针方向为 6 跳。注意:点数可能是奇数。 我希望你能理解我的问题..
最佳答案
尝试顺时针、逆时针并取最小值:
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));
关于c# - 计算较少的跳数 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710748/