Variables / Scramble arraylist elements in java

Suppose I have an arraylist of integers ... there is a way that I can generate a random permutation / arrangement of elements in an arraylist

therefore, if the list is {1,2,3,4,5,6}

calling some randomPermute () method will change it to something random, for example

{1,3,2,6,5,4}

+7
source share
3 answers

Collections.shuffle() does the job:

public static void shuffle(List<?> list) - Randomly rearrange the specified list using a random source randomly. All permutations occur with approximately equal probability. http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)

for example

  ArrayList<Integer>anArrayList = new ArrayList<Integer>(); anArrayList.add(1); anArrayList.add(2); anArrayList.add(3); anArrayList.add(4); anArrayList.add(5); System.out.println(anArrayList); Collections.shuffle(anArrayList); System.out.println(anArrayList); 

Output example

 [1, 2, 3, 4, 5] [3, 5, 1, 2, 4] 
+14
source

You can use Knuth shuffle : go through the positions from 1 to n-1, and for each position I will change the element, which there is an arbitrarily selected element from positions from i to n inclusive.

Edit: answer from hooch is better. :)

0
source

A simple example:

 ArrayList<MyObject> myObjects = new ArrayList<MyObject>(); //code -- load myObjects... Collections.shuffle(myObjects); 
0
source

All Articles