I am creating a new matrix where I want to take the rows of the original matrix and make them into columns as well as take the columns of the original matrix and make them into rows.
A matrix of:
[[1,2]
[3,4] [[1,3,5]
[5,6]] turns into [2,4,6]]
When I initialize the new matrix while using the fill() method to create my rows, the insertions duplicate for every row when inserting into a row.
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = new Array(matrix[0].length).fill(new Array()); // initializes array to [ [], [], [] ]
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print
[
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
]
When I initialize my array using a for loop, I do not get duplicate entries
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = [] // initializing using const transposedArr = Array() also works!
for(let i = 0; i < matrix[0].length; i++) { // initializes array to [ [], [], [] ]
transposedArr.push(new Array())
}
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print:
[
[ 1, 4, 7 ],
[ 2, 5, 8 ],
[ 3, 6, 9 ]
]
ASK : Why is it that when I initialize the array using the fill() method, it is duplicating my insertions for each row?
I came across this issue when working on this Leetcode problem: https://leetcode.com/problems/transpose-matrix/
I also tested this code in repl. It was to make sure it wasn't an issue in Leetcode's environment.
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; /* Allocate newMatrix array */ const newMatrix = []; for (const i in matrix) { const temp = []; for (const j in matrix[i]) temp.push(matrix[j][i]); newMatrix.push(temp); } console.log(newMatrix);
First of all, I have created and new array with the opposite length from the first array (Rows = Cols / Cols = Rows)
.
Then you just have to initialize the second array with [i][j] = [j][i]
so it will initialize the column of the original matrix to the row of the new one.
Hope you understood.
By the way fill method "fills" the array element to a STATIC value, and the parameters should be (value, start, end).
Documentation: Array.prototype.fill()
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.