badcoder
badcoder

Reputation: 3834

Java Random seed

I need to test out a Java program 20 times and need to set the random seed so that the tests can be repeated. If I were to set the initial seed as 0 and then increment by 1 at each run (i.e. 1,2,3 etc), would this method still ensure complete randomness, even though the seeds are not far apart?

Thank you

Upvotes: 3

Views: 7032

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533530

If you use a seed of 0 the sequence of random numbers will be repeatable from that point. You would only need to use a different random seed if you wanted a different sequence. i.e. you should be able to set the seed once per test.

Upvotes: 2

WhiteFang34
WhiteFang34

Reputation: 72049

Any seed will provide the same level of randomness as any other seed for a standard PRNG like the one included with Java. So it's fine to use an incrementing seed for tests.

You might want to consider using a better random number generator though. The one included with Java yields noticeable repeating patterns if you render the values as an image (I can't find a reference offhand, but I recall it being apparent). I'd recommend the Mersenne Twister (there are Java versions) as an alternative that's fast and has a very long period so you won't easily see patterns.

Upvotes: 6

lobster1234
lobster1234

Reputation: 7779

Do you need a number or a string? I use UUID.randomUUID().toString() to get a UUID for my tests when I need strings, but if you need a number then you can use System.nanoTime().

Upvotes: 0

ryanprayogo
ryanprayogo

Reputation: 11817

Why not just use the current time as the seed? ie, System.currentTimeMillis() ?

Upvotes: 1

Related Questions