Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm: Put y balls into x boxes where x <= y

Tags:

java

algorithm

I have a problem that comes up when I was developing an app on Android. However, the problem is:

There are x boxes and y balls where x <= y, and I want to distribute the balls to put them inside the boxes in order. For example: 3 boxes; box A, box B and box C - and 5 balls; ball 1, ball 2, ball 3, ball 4, ball 5.

What I need is to put the first ball ball 1 inside box A, and ball 5 inside box C and the other balls are distributed between them all (does not matter if one box has more balls than the others). Here is a loop (missing an increment value) that simulates the problem:

int boxCount = 0; // first box is 0 and last box is x
int numOfBalls = y;
for(int i = 0; i < numOfBalls; i++, boxCount += ???)
{
    boxes.get(boxCount).add(balls.get(i));
}

What equation should I used instead of ??? to solve the problem?


EDIT:

Since x <= y, that means:

  • None of the boxes should be empty.
  • The difference between the boxes' balls number should not be more than 1.

EDIT2

By in order, I meant this:

A   B   C
---------
1   3   5
2   4

not

A   B   C
---------
1   2   3
4   5
like image 599
Eng.Fouad Avatar asked Jan 17 '23 23:01

Eng.Fouad


2 Answers

int flag;
int lastBallAdded = 0;
int k = numOfBalls/numOfBoxes;
int m = numOfBalls%numOfBoxes;

for(int i = 0; i < numOfBoxes; i++, lastBallAdded+=k+flag) {
    flag = i<m;

    for(int j=lastBallAdded;j<lastBallAdded + k + flag;j++) 
        boxes.get(i).add(balls.get(j));
}

This is the reasoning behind this solution:

by the definition of the problem, the algorithm should put k= numOfBalls/numOfBoxes balls in each box, except for the firsts m = numOfBalls%numOfBoxes boxes, where you should put k+1 balls.

You can alternatively write it as

int i;
for(i = 0; i < m; i++) {
    //add k+1 balls
}

for(;i<numOfBoxes; i++) {
    //add k balls
}
like image 54
Manlio Avatar answered Jan 25 '23 22:01

Manlio


You can distribute (int)n/k balls in each of the first k-1 boxes and the rest in the last box. This will be simplest to code.

With this: boxCount += (i % (numOfBalls/numOfBoxes) == 0 && boxCount < numOfBoxes-1 ? 1 : 0)

like image 31
amit Avatar answered Jan 25 '23 22:01

amit