clayton33
clayton33

Reputation: 4216

android random number generator not random enough

I made a Yahtzee game where a player rolls 5 dice and use a random number generator to determine the dice values. The dice seem to be random enough when I run it on the emulator, but for some reason when I run it on some phones players keep getting the same values for many of the dice: too often for it to be a coincidence. For instance, if a 4 comes up on one dice, it often comes up on 3 or 4 other dice. What makes it hard to find the problem is that it isn't consistent: occasionally a throw will be normal. I determine the random numbers for all 5 dice using the following code:

public void randomDize(){
    int randSpot;

    for(int i = 0; i < 5; i++){
        Random randomGenerator = new Random();
        randSpot = randomGenerator.nextInt(6);
        if(DieSet[i]== 0){
            DieVal[i]=randSpot;
            imageButtons[i].setBackgroundResource(imageRes[randSpot]);
        }
    }       
}

Upvotes: 0

Views: 3065

Answers (1)

MByD
MByD

Reputation: 137382

You instantiate the random generator in the loop, move it outside:

private Random randomGenerator = new Random();
//or even:
// private static Random randomGenerator = new Random();
public void randomDize(){
    int randSpot;

    for(int i = 0; i < 5; i++){

        randSpot = randomGenerator.nextInt(6);
        if(DieSet[i]== 0){
            DieVal[i]=randSpot;
            imageButtons[i].setBackgroundResource(imageRes[randSpot]);
        }
    }       
}

Upvotes: 6

Related Questions