Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

permute/scramble arraylist elements in java

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

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

calling some method randomPermute() would change it to something random like

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

like image 641
kamikaze_pilot Avatar asked Feb 22 '11 04:02

kamikaze_pilot


1 Answers

Collections.shuffle() does the job:

public static void shuffle(List<?> list) - Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood. 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);

Sample Output

[1, 2, 3, 4, 5]
[3, 5, 1, 2, 4]
like image 53
hooch Avatar answered Nov 02 '22 16:11

hooch