c# - 计算较少的跳数 C#

标签 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/

相关文章:

c# - 如何从foreach中的其他元素列表中填充数组?

c# - 添加子菜单删除快捷键

c# - 为什么这个 Observable.Generate 重载会导致内存泄漏? [使用时间跨度 < 15ms]

c# - Crystal 报表显示空白页

c# - 生产者/消费者 msdn 示例如何工作?

c# - 将 IEnumerables 的 IEnumerable 转换为字典

c# - 编程策略——如何将对象向下传递到类链中

c# - 如何列出 N 值集的所有可能组合,其中每个值都来自使用 C# 的固定值子集?

c# - 如何在 Xamarin 中填充 TableView ?

c# - 如何在 C# 中向 mailto 添加附件?