11/10/2021

[Java] Distribute items in K buckets

Something simple which comes up often when problems require some sort of item distribution.

Given an amount of items N and K buckets, distribute the items in the buckets as uniformly as possible.

Amount of items each bucket would hold in perfect distribution: N/K (integer division)

Amount of remaining items which could make some buckets hold extra items compared to others: N%K

Therefore simply place N/K items in each bucket, then calculate the remainder N%K and place 1 item in each bucket until remainder is 0.

Of course if K is bigger than N, some buckets will be empty.

No comments:

Post a Comment

With great power comes great responsibility