【问题标题】:Round robin in C#C#中的循环
【发布时间】:2009-08-08 23:54:37
【问题描述】:

我在尝试用 C# 解决数学问题时遇到问题(可能是因为睡眠不足!)。

假设我有一台饮料机,我有三排可以装可乐的空行。我手里有 17 罐可乐,我必须一次装满每一排。

例如...

通过 1:

将可乐添加到第 1 行。饮料 = 1
将可乐添加到第 2 行。饮料 = 1
将可乐添加到第 3 行。饮料 = 1

通过 2:

将可乐添加到第 1 行。饮料 = 2
将可乐添加到第 2 行。饮料 = 2
将可乐添加到第 3 行。饮料 = 2

...

通过 6

将可乐添加到第 1 行。饮料 = 6
将可乐添加到第 2 行。饮料 = 6
将可乐添加到第 3 行。饮品 = 5(此时已无饮品)

出于某种原因,我完全迷路了。谁能帮忙?!

【问题讨论】:

  • 您的睡眠不足使您无法真正提出问题。你想做什么?
  • ??? int cans = 17; while(cans < -1) {...}???
  • 我不知道我要去哪里。:)

标签: c# logic


【解决方案1】:

非常快速和轻松,只需要一个循环,而不是两个嵌套循环。你只需要一点数学来获得数组的正确索引:

int[] Cola = {0,0,0};
int Rows = Cola.Length;
int Drinks = 17;

for (int i = Drinks; i > 0; i--)
{
   Cola[(Drinks - i) % Rows]++;
}

Console.WriteLine("Row 1 has " + Cola[0] + " cans.");
Console.WriteLine("Row 2 has " + Cola[1] + " cans.");
Console.WriteLine("Row 3 has " + Cola[2] + " cans.");

这会产生这个作为输出:

Row 1 has 6 cans.
Row 2 has 6 cans.
Row 3 has 5 cans.

【讨论】:

    【解决方案2】:

    您可以计算每行将获得多少罐,而不是循环添加一个罐子:

    int cans = 17;
    cans += machine.Rows.Count;
    for(int i = 1; i <= machine.Rows.Count; i++) {
       Console.WriteLine("Row {0} has {1} cans.", i, --cans / machine.Rows.Count);
    }
    

    【讨论】:

      【解决方案3】:

      从臀部射击:

      int numDrinks = /* Your constant here */
      int[] drinksInRow = new int[NUM_ROWS];
      for(int i = 0; i < drinksInRow.Length; i++)
      {
        drinksInRow[i] = numDrinks / NUM_ROWS;
        if(i < numDrinks % NUM_ROWS) drinksInRow[i]++;
      }
      

      每行饮料的数量在drinksInRow,从0开始的行号索引。

      这比重复遍历要快;基本上是它的 O(NUM_ROWS) [如果与 Big-O 玩真的松散]。

      【讨论】:

        猜你喜欢
        • 2013-11-05
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 2018-01-11
        • 1970-01-01
        • 2013-05-30
        • 1970-01-01
        • 2022-10-20
        相关资源
        最近更新 更多