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
This is the reasoning behind this solution:
by the definition of the problem, the algorithm should put
k= numOfBalls/numOfBoxesballs in each box, except for the firstsm = numOfBalls%numOfBoxesboxes, where you should putk+1balls.You can alternatively write it as