0

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 input = 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?

1
  • 1
    Left pad your numbers with 0s and you will see they are all 5-digit numbers ;) Commented May 19, 2011 at 14:38

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

As they say: the generation of random numbers is too important to be left to chance :)
6

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.