如何在数组中生成随机数加起来等于定义的总数? [英] How do I generate random numbers in an array that add up to a defined total?

查看:45
本文介绍了如何在数组中生成随机数加起来等于定义的总数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Java 中随机生成一个有 7 个插槽的数组.所有这些插槽的值必须至少为 1,但合并后的总值为另一个定义的数字.它们也都需要是 int 值,不能是 1.5 或 0.9816465684646 数字.示例:

I need to randomly generate an array with 7 slots in Java. All these slots must have a value of at LEAST 1, but combined, have a total value of another defined number. They also all need to be an int value, no 1.5 or 0.9816465684646 numbers. Example:

int a=10;

int[] ar = new int[7]
ar[0] = 1
ar[1] = 1
ar[2] = 2
ar[3] = 2
ar[4] = 1
ar[5] = 2
ar[6] = 1

我希望它生成类似的东西,但如果 int a=15,则所有数字的总和为 15,以任何顺序

I want it to generate something like that, but if int a=15, all the numbers would total 15 in any order

推荐答案

生成 N 个随机数并将其添加到给定总和的标准方法是将您的总和视为一条数轴,在该总和上生成 N-1 个随机点线,对它们进行排序,然后使用点之间的差异作为最终值.要获得最小的 1,首先从总和中减去 N,运行给定的算法,然后将 1 加回到每个部分.

The standard way to generate N random numbers that add to a given sum is to think of your sum as a number line, generate N-1 random points on the line, sort them, then use the differences between the points as your final values. To get the minimum 1, start by subtracting N from your sum, run the algorithm given, then add 1 back to each segment.

public class Rand {
    public static void main(String[] args) {
        int count = 8;
        int sum = 100;
        java.util.Random g = new java.util.Random();

        int vals[] = new int[count];
        sum -= count;

        for (int i = 0; i < count-1; ++i) {
            vals[i] = g.nextInt(sum);
        }
        vals[count-1] = sum;

        java.util.Arrays.sort(vals);
        for (int i = count-1; i > 0; --i) {
            vals[i] -= vals[i-1];
        }
        for (int i = 0; i < count; ++i) { ++vals[i]; }

        for (int i = 0; i < count; ++i) {
            System.out.printf("%4d", vals[i]);
        }
        System.out.printf("\n");
    }
}

这篇关于如何在数组中生成随机数加起来等于定义的总数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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