0

If I have a large multidimensional array (matrix), how can rearange the elements so that I have "y" values as the new "x" values in the array?

Hard to explain so let me give you an example. I want the below array.

[
[[0][1][2][3]],
[[4][5][6][7]],
[[8][9][10][11]],
[[12][13][14][15]],
]

to be transformed into the below array

[
[[0][4][8][12]],
[[1][5][9][13]],
[[2][6][10][14]],
[[3][7][11][15]],
]

for (var i = 0; i < tablesOfData.length; i++) {
   for (var j = 0; j < tablesOfData[i].length; j++) {
      //Transform the array
   }
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
user1825441
  • 507
  • 9
  • 13

1 Answers1

0

All rows needs to have the same number of columns.

If number of rows is the same as number of columns (like in your example), the following should work. If they are not the same then you need to create a n

for (var i = 0; < i tablesOfData.length; i++) {
    for (var j = i; j < tablesOfData.length; j++) {
        var temp = tablesOfData[i][j];
        tablesOfData[i][j] = tablesOfData[j][i];
        tablesOfData[j][i] = tablesOfData[i][j];
    }
}

Otherwise you need to create a new table and add the values to that table, like this:

var newTable = new int[tablesOfData[i].length]();

for (var i = 0; < i tablesOfData.length; i++) {
    for (var j = 0; j < tablesOfData.length; j++) {
        if (i == 0)
            newTable[j] = new int[tablesOfData.length]();

        newTable[j][i] = tablesOfData[i][j];
    }
}

I wrote the code in Notepad so it might not be the correct syntax to run on it's own but the logic should be right.

Sasse
  • 1,108
  • 10
  • 14