Distribute 'items' in buckets equally (best effort)
algorithm, distribution, java, math
Solution
This type of thinking should work:
package sandbox;
public class Sandbox
{
public static void main(String[] args)
{
int numBuckets = 12;
int numItems = 34;
int itemsPerBucket = (numItems / numBuckets);
int remainingItems = (numItems % numBuckets);
for (int i = 1; i <= numBuckets; i++)
{
int extra = (i <= remainingItems) ? 1:0;
System.out.println("bucket " + i + " contains " + (itemsPerBucket + extra) + " items.");
}
}
}
The output of this:
bucket 1 contains 3 items.
bucket 2 contains 3 items.
bucket 3 contains 3 items.
bucket 4 contains 3 items.
bucket 5 contains 3 items.
bucket 6 contains 3 items.
bucket 7 contains 3 items.
bucket 8 contains 3 items.
bucket 9 contains 3 items.
bucket 10 contains 3 items.
bucket 11 contains 2 items.
bucket 12 contains 2 items.
Notice the only looping you do is to talk about each bucket. You can easily just ask a bucket number and see how many items are in it without loop!
Problem
Say I want to distribute `y` items to `x` buckets evenly. If `x` is a multiple of `y` this distribution will be even, if not I can end up with `0` items in each bucket. For ex: For ex: I have `3` buckets and I want to distribute `2` items each. Since doing the division `(2/3)` will lead to `0` items per bucket. How can I achieve, a distribution of `1`, `1`, `0`?