Reputation: 53
Functions that output the transpose of a matrix - a new matrix where the columns and rows of the original are swapped. I'm trying to figure out why the second function outputs incorrect results?
function transpose(matrix) {
let res = [];
for(let i = 0; i < matrix[0].length; i++) {
res[i] = [];
for(let j = 0; j < matrix.length; j++) {
res[i][j] = matrix[j][i];
}
}
return res;
}
function transpose(matrix) {
let res = Array(matrix[0].length).fill([]);
for(let i = 0; i < res.length; i++) {
for(let j = 0; j < matrix.length; j++) {
res[i][j] = matrix[j][i];
}
}
return res;
}
Upvotes: 0
Views: 1388
Reputation: 81
I think the second function fails because of the let res
line. When you use .fill([])
, you are filling with the same array as givemesnacks mentions in this comment
If you do console.log(transpose([[1, 2, 3], [7, 4, 3]]))
, you'll notice that the elements in the array are the same.
To fix this, you can try let res = Array(matrix[0].length).fill().map(() => []);
, which should add a new empty array for every row.
function transpose(matrix) {
let res = Array(matrix[0].length).fill().map(() => []);
for (let i = 0; i < res.length; i++) {
for (let j = 0; j < matrix.length; j++) {
res[i][j] = matrix[j][i];
}
}
return res;
}
let m = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
console.log(transpose(m))
Upvotes: 2