how to shuffle a 2D array in java correctly?

Java 8Object Oriented ProgrammingProgramming

Yes. Create a list to represent a 2D array and then use Collections.shuffle(list).

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      List<int[]> rows = new ArrayList<>();
      rows.add(new int[]{1,2,3});
      rows.add(new int[]{4,5,6});
      rows.add(new int[]{7,8,9});
      System.out.println("Before Shuffle");
      System.out.println("[0][0] : " + rows.get(0)[0]);
      System.out.println("[1][1] : " + rows.get(1)[1]);
      System.out.println("After Shuffle");
      Collections.shuffle(rows);
      System.out.println("[0][0] : " + rows.get(0)[0]);
      System.out.println("[1][1] : " + rows.get(1)[1]);
   }
}

Output

Before Shuffle
[0][0] : 1
[1][1] : 5
After Shuffle
[0][0] : 7
[1][1] : 2
raja
Published on 06-Feb-2018 11:48:40
Advertisements