-2

Is there a simple way to randomize the order of columns in a 2d array? For example could I use it to randomize the columns of this 2d array

int[][] dataArray = {{1, 1, 0, 1, 0, 0}, 
                     {0, 0, 1, 0, 1, 1},
                     {1, 1, 1, 1, 1, 1}, 
                    {0, 0, 0, 0, 1, 1}};

I have been trying for awhile with little luck so far. What i am trying to do is make columns 1 2 3 4 5 6 randomly become columns 2 3 1 6 5 4 for example. I have tried randomly drawing numbers and trying to make the columns match the order but i can't seem to get that working.

EDToaster
  • 3,160
  • 3
  • 16
  • 25

1 Answers1

0

You could always construct a 1D array, randomize its contents, then reconstruct a 2D array.

int[] newArray = new int[a.length + b.length + c.length + d.length]; 
// where a, b, c, and d are the smaller arrays inside dataArray
System.arrayCopy(a, 0, newArray, 0, a.length);
System.arrayCopy(b, 0, newArray, a.length, b.length);
System.arrayCopy(c, 0, newArray, a.length + b.length, c.length);
System.arrayCopy(d, 0, newArray, a.length + b.length + c.length, d.length);

This will construct a 1D array called newArray that has the contents of all the smaller arrays.

Now randomize that array as shown here.

Then to reconstruct the original array:

int newArray2d[][] = new int[5][4]; //do this dynamically based on the size of the first array.
for(int i=0; i<5;i++)
   for(int j=0;j<4;j++)
       array2d[i][j] = array1d[(j*10) + i]; 
Community
  • 1
  • 1
Jamie Counsell
  • 7,730
  • 6
  • 46
  • 81