FishyK
FishyK

Reputation: 169

Why would you add a random variable to the shuffle method?

I don't understand the use of an additional random inside the shuffle method. From the examples I've seen so far, there's not benefit to it, or is there? It says that it specifies the source of randomness, however, isn't the shuffle method in itself random? So why would I want to specify it any further?

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

//What is the difference?
Collection.shuffle(list);
Collection.shuffle(list, new Random(2));

Upvotes: 0

Views: 244

Answers (2)

pjs
pjs

Reputation: 19855

There are two big reasons you might want to provide a source of randomness other than the default one:

  1. reproducibility; and
  2. to use a better Pseudo-Random Number Generator (PRNG).

#1 — The sequence of values shuffle() uses to perform the shuffle, and therefore the order of the results, depends on the state of the generator at the time you call the shuffle method. If you clone your list, and call shuffle() on the original list and then on its clone using the default PRNG, you will get two different results. Similarly, if you or somebody else runs your program multiple times, each run will result in a different shuffle because the PRNG seed will be different. Reproducibility of results is essential for debugging, and also for allowing colleagues to validate your results in research. To achieve reproducibility, pass shuffle() a Random object which has a fixed seed.

#2 — Java's implementation of Random is a 48 bit Linear Congruential Generator. Not bad, but not great either. If you wish to use a third-party generator such as WELL or variations on xoroshiro, you can do so by calling shuffle() with the desired alternate PRNG.

Upvotes: 1

BBonless
BBonless

Reputation: 127

The random argument specifies the source of randomness

If you create two random objects with the same seed, then shuffle 2 lists using those objects like so:

Random R1 = new Random(1);
Random R2 = new Random(1); //Same seeds

Collections.shuffle(List1, R1);
Collections.shuffle(List2, R2);

Both the lists will then be shuffled in the same order. If the lists are identical, then the result will also be identical.

Its useful if you for some reason you need randomly generated things to be replicable. For example in Minecraft, worlds are randomly generated - but players can share the seed that generated the world so that other people can generate the exact same world.

Upvotes: 1

Related Questions