user1713336
user1713336

Reputation: 129

Effectiveness of Collections.shuffle

I'm trying to create a lottery simulator in java and I'm beginning to become concerned about whether my generated numbers are random enough.

For example, my code for generating white ball numbers that are non repeating looks like this.

public static int[] genWhiteNums()
{
    int[] whitePicks = new int[5];
    Collections.shuffle(whiteDrawNums); //whiteDrawNums is an arraylist of numbers 1-59

    for(int i = 0; i < 5; i++)
    {
        whitePicks[i] = whiteDrawNums.get(i);
    }
    whiteDrawNums = createWhiteNums(); //Reordering

    return whitePicks;
}

Is picking the first 5 values from Collections.shuffle random enough?

Upvotes: 0

Views: 341

Answers (3)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Use Random#nextInt() to pick sufficiently distributed random values from your shuffled collection.

public static int[] genWhiteNums() {
    Random random = new Random();

    int[] whitePicks = new int[5];
    Collections.shuffle(whiteDrawNums);  // Arraylist 1-59

    for (int i = 0; i < whitePicks.length; i++) {
        whitePicks[i] = whiteDrawNums.get(
                        random.nextInt(i != 4 ? 12 : 11) + 12 * i);
    }

    whiteDrawNums = createWhiteNums(); // Reordering
    return whitePicks;
}

It's splitting the available indexes (0-58) into 4 groups of 12 and the last group of 11 and picking one random index every iteration of the loop. This should suffice your need for randomness adequately.

Upvotes: 0

stinepike
stinepike

Reputation: 54742

According to the doc here

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

The hedge "approximately" is used in the foregoing description because default source of randomenss is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.

It uses a linear time shuffling algorithm. I think it is random enough to meet most people's need.

Upvotes: 3

Evans
Evans

Reputation: 1599

Collections.shuffle does a Fisher-Yates shuffle. Its in your considerations if it´s random enough

Upvotes: 2

Related Questions