Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collections.Shuffle only shuffling once

I have a piece of code, and the idea is that it takes in an array list with n amount of numbers and shuffles it 50 times and adds each time adds the new shuffle to another array list.

However what it seems to do is shuffle it once, add it to the array list (Like is should), but for the next 49 times, it doesnt shuffle it. It only adds the same one. You may understand more from my code below:

int chromeSize;
ArrayList<GeoPoint> geoPoints = new ArrayList<GeoPoint>();      
ArrayList<Integer> addToFirstChrome = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> populationShuffle = new ArrayList<ArrayList<Integer>>();

for (int i=0; i<geoPoints.size(); i++) {
  addToFirstChrome.add(i);
}
System.out.println("add To First Chrome " + addToFirstChrome);

for (int j =0; j<50; j++) {
  Collections.shuffle(addToFirstChrome);
  populationShuffle.add(addToFirstChrome);
}  

for (int p=0;p<populationShuffle.size();p++) {
  System.out.println("Pop " + p +"=" + populationShuffle.get(p));
}

And here is a sample of the output:

10-02 10:10:26.785: I/System.out(19648): add To First Chrome [0, 1, 2, 3, 4]
10-02 10:10:26.790: I/System.out(19648): Pop 0=[2, 1, 3, 4, 0]
10-02 10:10:26.790: I/System.out(19648): Pop 1=[2, 1, 3, 4, 0]
10-02 10:10:26.790: I/System.out(19648): Pop 2=[2, 1, 3, 4, 0]
10-02 10:10:26.790: I/System.out(19648): Pop 3=[2, 1, 3, 4, 0]
10-02 10:10:26.790: I/System.out(19648): Pop 4=[2, 1, 3, 4, 0]

So as you see, it shuffles the first one, but not anymore. Am i missing something here?

like image 298
James King Avatar asked Feb 18 '23 23:02

James King


1 Answers

Am i missing something here?

Yes. You're missing the fact that you're adding the same reference on each iteration:

for(int j =0; j<50; j++) {
    Collections.shuffle(addToFirstChrome);
    populationShuffle.add(addToFirstChrome);
}

That's effectively the same as:

for (int j =0; j < 50; j++) {
    Collections.shuffle(addToFirstChrome);
}
for (int j = 0; j < 50; j++) {
    populationShuffle.add(addToFirstChrome);
}

The value of addToFirstChrome is just a reference.

It sounds like you want 50 separate collections, in which case you need to create a new collection on each iteration:

for (int j = 0; j < 50; j++) {
    List<Integer> copy = new ArrayList<Integer>(addToFirstChrome);
    Collections.shuffle(copy);
    populationShuffle.add(copy);
}

(Note that this requires you to change the type of populationShuffle to List<List<Integer>> or ArrayList<List<Integer>> - prefer programming to interfaces where possible.)

like image 126
Jon Skeet Avatar answered Feb 21 '23 14:02

Jon Skeet