0

I am trying to generate 100 random permutations of an array and then store each of these random permutations within an ArrayList. Currently this isn't working I am able to generate one random permutation but the same one is stored 100 times

public void generatePermutations() {
    int[] currentList = this.listOfItems;
    int index, temp;
    Random random = new Random();
    
    for(int j = 0 ; j < 100; j++) { 
        
        for (int i = currentList.length - 1; i > 0; i--) {
            index = random.nextInt(i + 1);
            temp = currentList[index];
            currentList[index] = currentList[i];
            currentList[i] = temp;
            }
        permutationsList.add(currentList);
        }
    }

current output

 [23, 45, 34, 53, 67, 99, 3, 0,13, 2, 12, 8] //the same permutation generated 100 times
  • Just a note: Prefer using `ThreadLocalRandom.current()` instead of `new Random()`, its faster and has nicer methods. – Zabuzard Nov 03 '20 at 17:10
  • 2
    It's not an exact duplicate, but describes what your problem is (Adding the same object again and again). To solve this simply create a copy of your array when adding it: `permutationsList.add(Arrays.copyOf(currentList, currentList.length));` – OH GOD SPIDERS Nov 03 '20 at 17:12
  • @OHGODSPIDERS thanks managed to get it working with the change you suggested –  Nov 03 '20 at 17:15

0 Answers0