一尘不染

将“项目”平均分配到存储桶中(尽最大努力)

algorithm

假设我想将y物品x平均分配到水桶中。如果x是,则y此分布的倍数将是偶数,如果不是,则可以得到0每个存储桶中的项目。例如:

例如:我有3水桶,我想2每个都分发物品。由于进行除法,(2/3)将导致0每个存储桶中的项目。如何能够做到,分布110


阅读 321

收藏
2020-07-28

共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.

请注意,您要做的唯一循环是谈论每个存储桶。您可以轻松地询问一个存储桶编号,看看其中有多少个项目而没有循环!

2020-07-28