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]
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(' '));
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.
var arr1 = [];
var arr2 = [];
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
arr1.push(mat[i][j]);
}
}
for(int j=0; j<mat[i].length; j++) {
for(int i=0; i<mat.length; i++) {
arr2.push(mat[i][j]);
}
}
Set a max "width" for your matrix and insert into a new array in loops, offset by 1 for each run.
function transpose(list, width) { if (width === void 0) { width = 1; } var t = 0; var transposed = []; while (t < width) { for (var index = t; index < list.length; index += width) { transposed.push(list[index]); } t++; } return transposed; } //TEST var list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var transposed = transpose(list, 3); console.log(list.join()); console.log(transposed.join());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.