lundi 23 novembre 2015

Why does this random generator return the same result over and over?

I wrote this to generate random Candidate objects to fill the ArrayList pop. Each Candidate holds an array, and this code its supposed to generate a different array for each Candidate:

ArrayList<Candidate> pop = new ArrayList<>();
int skinThicknes, attackDamage ,skinCoulor, canFly, canSwing, speed, flySpeed, swingSpeed, num = 0;
Random rnd;
rnd = new Random();
while(num < size) {

    skinThicknes = rnd.nextInt(101);
    attackDamage = rnd.nextInt(101);
    skinCoulor = rnd.nextInt(3);
    canFly = rnd.nextInt(1);
    canSwing = rnd.nextInt(1);
    speed = rnd.nextInt(1001);
    flySpeed = rnd.nextInt(1001);
    swingSpeed = rnd.nextInt(1001);
    if(canFly == 0){flySpeed = 0;}
    if(canSwing == 0){swingSpeed  = 0;}
    int[] array = {skinThicknes, attackDamage, skinCoulor, canFly, canSwing, speed, flySpeed, swingSpeed};
    Candidate can;
    can = new Candidate(array);
    pop.add(can);
    num++;
}
return pop;

Why are the arrays of every Candidate in pop equal?


This is the constructor for Candidate. All those variables (skinTicknes, attackDamage, etc.) are private static ints.

public Candidate(int[] geno){
    skinTicknes = geno[0];
    attackDamage = geno[1];
    skinCoulor = geno[2];
    canFly = geno[3];
    canSwing = geno[4];
    speed = geno[5];
    flySpeed = geno[6];
    swingSpeed = geno[7];
}




Aucun commentaire:

Enregistrer un commentaire