假设我想将y物品x平均分配到水桶中。如果x是,则y此分布的倍数将是偶数,如果不是,则可以得到0每个存储桶中的项目。例如:
y
x
0
例如:我有3水桶,我想2每个都分发物品。由于进行除法,(2/3)将导致0每个存储桶中的项目。如何能够做到,分布1,1,0?
3
2
(2/3)
1
这种想法应该起作用:
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."); } } }
此输出:
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.
请注意,您要做的唯一循环是谈论每个存储桶。您可以轻松地询问一个存储桶编号,看看其中有多少个项目而没有循环!