tags:

views:

491

answers:

3

I'm having a problem (possibly due to lack of sleep!) where I'm trying to solve a maths problem in C#.

Let's say I have a drinks machine, and I have three empty rows that can be filled with Cola. I have 17 cans of Cola in my hand and I have to fill each row one at a time.

For example...

Pass 1:

Add Cola to Row 1. Drinks = 1

Add Cola to Row 2. Drinks = 1

Add Cola to Row 3. Drinks = 1

Pass 2:

Add Cola to Row 1. Drinks = 2

Add Cola to Row 2. Drinks = 2

Add Cola to Row 3. Drinks = 2

...

Pass 6

Add Cola to Row 1. Drinks = 6

Add Cola to Row 2. Drinks = 6

Add Cola to Row 3. Drinks = 5 (no more drinks left at this point.

For some reason, I'm completely lost. Can anyone help?!

+2  A: 

Pretty quick and painless, and only requires one loop, not two nested loops. All you need is a little bit of math to get the correct index of the array:

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.");

This produces this as output:

Row 1 has 6 cans.
Row 2 has 6 cans.
Row 3 has 5 cans.
Eric
Do you know, that's absolutely right!
Dan Atkinson
Thank you for your response!
Dan Atkinson
Quite welcome, glad it's helped. Have fun and good luck.
Eric
+1  A: 

Shooting from the hip:

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]++;
}

number of drinks in each row is in drinksInRow, indexed by row number starting from 0.

This is faster than doing repeated passes; basicallys its O(NUM_ROWS) [if playing really loose with Big-O].

Kevin Montrose
+2  A: 

Instead of looping to add a can at a time, you can calculate how many cans each row will get:

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);
}
Guffa