代码之家  ›  专栏  ›  技术社区  ›  Dan Atkinson

C循环赛#

  •  3
  • Dan Atkinson  · 技术社区  · 17 年前

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



    通行证2:



    通过6


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

    3 回复  |  直到 15 年前
        1
  •  5
  •   Eric    17 年前

    非常快速和无痛,只需要一个循环,而不是两个嵌套循环。你只需要一点数学运算就可以得到数组的正确索引:

    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
  •  2
  •   Guffa    17 年前

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

    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
  •  1
  •   Kevin Montrose    17 年前

    从臀部射击:

    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开始的行号索引。

    与Big-O松散]。

    推荐文章