- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixTranspose.js
More file actions
Latest commit
53 lines (41 loc) · 1.47 KB
/
Copy pathMatrixTranspose.js
File metadata and controls
53 lines (41 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// ------------------------------------------Description----------------------------------------------------------
// Write a function that outputs the transpose of a matrix - a new matrix where the columns and rows of the original are swapped.
// For example, the transpose of:
// | 1 2 3 |
// | 4 5 6 |
// is
// | 1 4 |
// | 2 5 |
// | 3 6 |
// The input to your function will be an array of matrix rows. You can assume that each row has the same length, and that the height and width of the matrix are both positive.
// ---------------------------------------------------------------------------------------------------------------
consttranspose=(matrix)=>{
// Determine the dimensions of the transposed matrix
constnumRows=matrix.length;
constnumCols=matrix[0].length;
// Create a new matrix with the transposed dimensions
consttransposed=newArray(numCols);
for(leti=0;i<numCols;i++){
transposed[i]=newArray(numRows);
}
// Populate the transposed matrix
for(leti=0;i<numRows;i++){
for(letj=0;j<numCols;j++){
transposed[j][i]=matrix[i][j];
}
}
returntransposed;
};
constmatrix1=[
[1,2,3],
[4,5,6],
];
constmatrix2=[
[1,2],
[3,4],
[5,6],
];
constmatrix3=[[1]];
console.log(transpose(matrix1));// Expected output: [[1, 4], [2, 5], [3, 6]]
console.log(transpose(matrix2));// Expected output: [[1, 3, 5], [2, 4, 6]]
console.log(transpose(matrix3));// Expected output: [[1]]