Java Array multidimensional Arrays shuffle

Description

Java Array multidimensional Arrays shuffle


import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    int[][] array = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    System.out.println(Arrays.deepToString(array));
    //from   ww  w  .  j  av  a  2 s. c  om
    array = randomShuffle(array); 
    
    System.out.println(Arrays.deepToString(array));
  }

  public static int[][] randomShuffle(int[][] matrix) {

    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        int i1 = (int) (Math.random() * matrix.length);
        int j1 = (int) (Math.random() * matrix[i].length);

        // Swap matrix[i][j] with matrix[i1][j1]

        int temp = matrix[i][j];
        matrix[i][j] = matrix[i1][j1];
        matrix[i1][j1] = temp;
      }
    }
    return matrix;
  }

}



PreviousNext

Related