Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose 2D square matrix stored as 1D array in Javascript

My question is closely related to this question but I'm looking for a solution in Javascript

How to Transpose 2D Matrix Stored as C 1D Array

Basically I have a 2D square matrix

1 2 3
4 5 6
7 8 9

Stored as follows

let anArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9]

How can I transpose this matrix so that the elements of my source array are switched as follows?

let newArray = [1, 4, 7, 2, 5, 8, 3, 6, 9] 
like image 315
ScottMcC Avatar asked Aug 13 '18 06:08

ScottMcC


People also ask

What is transpose of a two-dimensional array in JavaScript?

Transpose of a two-dimensional array - JavaScript 1 Transpose. The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). 2 Example 3 Output

How to transpose a matrix (2-D array)?

The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). We can transpose a matrix (2-D array) by switching its rows with its columns.

What is transpose in Matplotlib?

1 Transpose. The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). 2 Example 3 Output

What is the difference between axes and transpose in JavaScript?

axes: By default the value is None. When None or no value is passed it will reverse the dimensions of array arr. The axes parameter takes a list of integers as the value to permute the given array arr. The transpose of the 1-D array is the same. The output of the transpose () function on the 1-D array does not change.


2 Answers

You could take the length for the dimension of the array and map items on a specific index for a new array.

var array = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
    n = Math.sqrt(array.length),
    transposed = array.map((_, i, a) => a[(i % n) * n + Math.floor(i / n)]);
    
console.log(transposed.join(' '));
like image 126
Nina Scholz Avatar answered Nov 15 '22 00:11

Nina Scholz


The approach in the answer you linked to works well in JavaScript too.

For a 3 x 3:

const anArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let newArray = [];
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    newArray[3 * i + j] = anArray[3 * j + i];
  }
}

console.log(newArray);

For an N x N, just replace the 3's with N.

This answer avoids division and flooring (integer division) and a decent optimizer should make the code relatively fast. You might also consider initializing the new array with

let newArray = new Array(9);

or

let newArray = new Array(N * N);

but profile the code before attempting "optimizations" such as this.

like image 24
Ray Toal Avatar answered Nov 14 '22 22:11

Ray Toal