how to shuffle a 2D array in java correctly?


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

Updated on: 24-Feb-2020

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements