产生随机整数的具有非均匀分布的阵列 [英] Generate an array of random integers with non-uniform distribution

查看:279
本文介绍了产生随机整数的具有非均匀分布的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写Java code产生随机整数数组范围为[1,4]。数组的长度为N,它在运行时提供。问题是,该范围[1,4]不是均匀分布:

I want to write Java code to produce an array of random integers in the range [1,4]. The array's length is N, which is provided at run time. The problem is that the range [1,4] is not uniformly distributed:

这意味着,如果我创建阵列具有N = 100,数​​字1将在一个阵列,数出现平均40次2的10倍,并依此类推。

It means that if I create arrays with N=100, the number '1' will appear averagely 40 times in an array, number '2' 10 times, and so on.

现在我用这code的范围内产生均匀分布的随机数[1,4]:

For now I am using this code to generate uniform-distributed random numbers in range [1,4]:

public static void main(String[] args)
    {
        int N;
        System.out.println();
        System.out.print("Enter an integer number: ");
        N = input.nextInt();
        int[] a = new int[N];
        Random generator = new Random();
        for(int i = 0; i < a.length; i++)
        {
            a[i] = generator.nextInt(4)+1;
        }
    }

怎样与实现它的非均匀分布,如图中上面的曲线图

How do I implement it with a the non-uniform distribution as shown in the graph above?

推荐答案

下面是一个办法做到这一点,从code启动:

Here's a way to do it, starting from your code:

public static void main(String[] args){
    int N;
    System.out.println();
    System.out.print("Enter an integer number: ");
    N = input.nextInt();
    int[] a = new int[N];
    Random generator = new Random();
    for (int i = 0; i < a.length; i++) {
        float n = generator.nextFloat();
        if (n <= 0.4) {
            a[i] = 1;
        } else if (n <= 0.7) {
            a[i] = 3;
        } else if (n <= 0.9) {
            a[i] = 4;
        } else {
            a[i] = 2;
        }
    }
}

更新:在@pjs的建议,在desdencing概率高的顺序选择号码所以你往往会更早退出if块

UPDATE: at @pjs' suggestion, select numbers in order of desdencing probability so you tend to exit the if block earlier

这篇关于产生随机整数的具有非均匀分布的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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