Itsik
Itsik

Reputation: 3930

Creating a set of uniformly distributed random numbers

I have a list of N objects.
I would like to insert X dummy objects which are randomly placed between the real N objects, spaced between (0, N).

So I tried the following code.

int[] dummyIndexes = new int[X];
int randomStep = N/X * 2; // *2 because the Mean is N/X/2

Random random = new Random();
int randIdx = 0;

for (int i=0; i < X; i++)
{ 
   randIdx += random.nextInt(randomStep);
   dummyIndexes[i] = randIdx;
}

This works alright, although I'm not getting a good distribution all the way to the end of the domain N.

What's a better way to do this ?

Upvotes: 3

Views: 2294

Answers (2)

Frank
Frank

Reputation: 15641

This will do the trick (but note that it will newer place anything at N, the largest value will be N-1)

    int[] dummyIndexes = new int[X];
    int randomStep = N/X;
    Random random = new Random();
    int randIdx = 0;
    for (int i=0; i < X; i++)
    { 
       randIdx = randomStep * i  + random.nextInt(randomStep);
       dummyIndexes[i] = randIdx;
    }

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

This is will ensure you have one random value between each N/X

 randIdx = N * i / X + random.nextInt(N / X) + 1;

Upvotes: 1

Related Questions