分发 'items'在桶中相等(尽力而为) [英] Distribute 'items' in buckets equally (best effort)

查看:16
本文介绍了分发 'items'在桶中相等(尽力而为)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想将 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!

这篇关于分发 &amp;#39;items&amp;#39;在桶中相等(尽力而为)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆