jeudi 27 août 2015

Random() always picks the same number using a seed

I have a very strange bug that I am trying to fix. I will try my best to explain it.

I have a class, and in that class I have a method that picks a random number. The random number generation has to generate the exact same sequence of numbers every time I run the application (different numbers, but appear in the same order no matter when I run the app).

Therefore I need to use seeds.

My code looks something like this:

    public class Tree{
    Random rand = new Random(12345);

///...code...///

         public Tree randomNode() {

              //HERE IS THE ERROR
              int r = rand.nextInt(this.size);

              if (r == 0) {
                 return this;

              } 
              else if (left != null && 1 <= r && r <= left.size) {
                 return left.randomNode();
              } 
              else {
                 return right.randomNode();
              }
           }
        }

I have a helper class that uses this, it looks a bit like this:

   public Crossover(Tree p1, Tree p2)
   {
      Tree subtreeP1 = p1.randomNode();
      Tree subtreeP2 = p2.randomNode();
   }

My main method looks a bit like this:

for(i=0;i<cross;i++)
{
Crossover c = new Crossover(p1,p2);
}

During the first loop in the main method, the numbers for r generate randomly and are fine. However, on the 2nd loop (and all that follow) is where I encounter the problem. The problem is on the line int r = rand.nextInt(this.size); - After the 2nd loop I ALWAYS get 0 no matter what.

If I remove the seed, all works well. If I include the seed, I start getting 0 ALWAYS after the first loop.

How can I continue using a seed, but get random numbers? And what am I doing wrong?

**EDIT: **

this.size refers to the size of my tree. I have ensured it is NOT zero when I get r to be 0. ALSO I would like to point out, that when I simply remove the number seed, it works fine, and random number generation works fine. When I add the seed, I have the problem.




Aucun commentaire:

Enregistrer un commentaire