CodeWars 코딩 문제 2021/01/08 - Matrix Transpose

이호현·2021년 1월 8일
0

Algorithm

목록 보기
47/138

[문제]

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하게 하면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글