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.
(요약) 행렬의 행을 열로, 열을 행으로 요소를 바꿔라.
function transpose(matrix) { const answer = []; const rowLength = matrix.length; const columnLength = matrix[0].length; for(let i = 0; i < rowLength; i++) { for(let j = 0; j < columnLength; j++) { if(!i) { answer.push([matrix[i][j]]); } else { answer[j].push(matrix[i][j]); } } } return answer }
인자로 받은 2차원 배열의 행과 열의 길이를 구하고,
반복문을 이용해서 행 요소들을 열 요소로 순차적으로push
하게 함.
첫 행일 때는 첫 행 요소가 담긴 배열을push
하게 하고, 2번째 행부터는 순차적으로push
하게 하면 됨.