Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a seed to shuffle ArrayList in Java deterministically

Tags:

java

random

I have a list of integers (currently using cern.colt.list.IntArrayList). I can call "shuffle()" and randomly shuffle them. I would like to be able to reproduce a shuffle. I can reproduce a series of random numbers by setting a seed. I do not seem to be able to set a seed in this case. What should I do? I am open to other implementations.

like image 272
Ben Flynn Avatar asked Jun 08 '11 20:06

Ben Flynn


People also ask

Can you shuffle an ArrayList Java?

We can create a list from the array and then use the Collections class shuffle() method to shuffle its elements. Then convert the list to the original array.

How do you shuffle items in an ArrayList?

In order to shuffle elements of ArrayList with Java Collections, we use the Collections. shuffle() method. The java. util.

Can you shuffle a set in Java?

Set is unordered, so randomizing an unordered Collection doesn't make any logical sense. An ordered Set is ordered using a Comparator which means it has a fixed order, you can't shuffle it, that has no meaning as the order is determined by the Comparator or the compare() method.


3 Answers

This is possible by using the shuffle method that allows you to provide the backing Random instance: Collections.shuffle(List<?> list, Random rnd):

Example:

Collections.shuffle(yourList, new Random(somePredefinedSeed)); 
like image 195
aioobe Avatar answered Sep 18 '22 23:09

aioobe


You can specify the Random instance with a seed value using public static void shuffle(List list, Random rnd). For the Random(long seed) constructor you can specify a seed.

From Java Docs:

Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.

like image 44
CoolBeans Avatar answered Sep 18 '22 23:09

CoolBeans


there is an alternative method which takes a Random as source

like image 45
Peter Tillemans Avatar answered Sep 19 '22 23:09

Peter Tillemans