开发者

Issues with generating array of integer numbers randomly in java

I am trying to generate an array with N integer values between 0 and 100000.

Here is the code:

import java.util.*;
public class Main
{

    public static Scanner in开发者_Go百科put = new Scanner(System.in);

    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(100001);
        }
    }
}

What I notice that, at every time I generate new array, most of the integer numbers in the array is 5-digit numbers, sometimes there are 4-digit numbers, and rarely there are 3-digit numbers, but never happened that I found 2-digit or fewer numbers.

is my implementation wrong?


Consider how many numbers there are of each kind:

  • 1 6-digit number
  • 90000 5-digit numbers
  • 9000 4-digit numbers
  • 900 3-digit numbers
  • 90 2-digit numbers
  • 10 1-digit numbers (including 0)

So ~90% of your numbers should be 5-digit numbers, and only about 1% of the numbers should be 3 digits or fewer. They'll happen, but very rarely.


What seems to be wrong is your perception that this is in any way odd.

Of the numbers between 0 and 100000, there is only 1 that has 6 digits, about 90% have 5 digits, 9% have 4 digits, 0.9% have 3 digits, and only 0.09% have 1 or 2 digits. So given a uniform distribution (which nextInt() implements), it's not at all odd that you don't see them much or at all. If you want a different distribution, you'll have to implement it yourself.


Think about it... There are 9 * 10 ^ (n-1) numbers with n digits. That means there are 90000 5 digit numbers and only 900 3 digit numbers. On average you should expect to see only one 3 digit number for each 100 5 digit numbers, and only one single digit number per 10000 5 digit numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜