本文介绍了将“项目"平均分配到存储桶中(尽最大努力)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想将y个项目平均分配到x个存储桶中.如果xy的倍数,则该分布将是偶数,如果不是,那么我可以在每个存储桶中得到0项.例如:

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:

例如:我有3个存储桶,我想分别分发2个项目.由于执行除法(2/3)将导致每个存储桶中的0个项目.如何实现110的分布?

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?

推荐答案

这种类型的思维应该起作用:

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.");
        }
    }
}

此输出:

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!

这篇关于将“项目"平均分配到存储桶中(尽最大努力)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 23:59