Dhruv Gairola
Dhruv Gairola

Reputation: 9182

Java Random: Seeding Problem

was wondering if you could help me out:

I have a method called initializeAll:

public final void initializeAll() {
//other stuff........
rand = new Random(353);
}

So I run the project and a GUI pops up, and some operations are carried out. When I press the "reset" button in my GUI, intializeAll is called again on the same class object. However, the operations that are carried out now are not the same as before, although they should be, since both times, a seed of 353 is being used on the newly created Random object. Why this difference? Am I doing something wrong?

EDIT: sorry, its not "some operations are carried out". its that some initialization of agent population takes place. and each time, the initialization is different, although the same seed is used.

    private static int [][] initializePop(Random rand) {
        int[][] temp = new int[ROWS][COLS];
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                temp[row][col] = rand.nextInt(12) - 5;
            }
        }
        return temp;
    }

SOLUTION:

sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. i'm redesigning the code now. so thanks again, and sorry for wasting your time.

Upvotes: 1

Views: 789

Answers (2)

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. so thanks again, and sorry for wasting your time.

Upvotes: 0

aioobe
aioobe

Reputation: 421030

Am I doing something wrong?

Yes, it seems so. The Random(long) should reset the seed to the provided value. What ever the error is, it will be impossible for us to help you without an SSCCE or at least more code.

Random rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));

rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));

Output:

7
5
5
7
5
5

Upvotes: 2

Related Questions