Shuffling Elements of a two-dimensional array

Problem:

In a java program, create random numbers in a two-dimensional array, then shuffle them!

Output:

Original array:
24 38 15
19 63 7
87 76 57

Shuffled array:
24 38 19
63 87 15
76 57 7


Solution:

public class twoDimentionalArrays
{
  public static void main (String[] args)
  {
    int[][] list = new int[3][3];
    for (int i =0;i<list.length;i++)
    {
      for (int j=0; j<list[0].length;j++)
      {
        list[i][j] = (int) (Math.random()*100);
      }
    }
    System.out.println("Original array:");
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");

      }
      System.out.println();
    }
    
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        int i1 = (int) (Math.random()*list.length);
        int j1 = (int) (Math.random()*list[j].length);
        
        int temp = list[i][j];
        list[i][j] = list[i1][j1];
        list[i1][j1] = temp;
      }
    }
    System.out.println();
    System.out.println("Shuffeled array:");
    for (int i =0;i<list.length;i++)
    {
      for(int j =0;j<list[0].length;j++)
      {
        System.out.print(list[i][j] + "\t");

      }
      System.out.println();
    }
  }
}


1 comment :

  1. Could you please leave comments so it's a bit easier to read?

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact