Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript의 정사각 행렬 회전

<시간/>

우리는 n * n 차수(정사각 행렬)의 배열 배열을 취하는 JavaScript 함수를 작성해야 합니다. 함수는 배열을 90도(시계 방향) 회전해야 합니다. 조건은 이 작업을 제자리에서 수행해야 한다는 것입니다(추가 배열을 할당하지 않고).

예:

입력 배열이 -

인 경우
const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

그러면 회전된 배열은 다음과 같아야 합니다. -

const output = [
   [7, 4, 1],
   [8, 5, 2],
   [9, 6, 3],
];

예시

다음은 코드입니다 -

const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
const rotateArray = (arr = []) => {
   for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
      for (let columnIndex = rowIndex + 1; columnIndex < arr.length;
      columnIndex += 1) {
         [
            arr[columnIndex][rowIndex],
            arr[rowIndex][columnIndex],
         ] = [
            arr[rowIndex][columnIndex],
            arr[columnIndex][rowIndex],
         ];
      }
   }
   for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
      for (let columnIndex = 0; columnIndex < arr.length / 2;
      columnIndex += 1) {
         [
            arr[rowIndex][arr.length - columnIndex - 1],
            arr[rowIndex][columnIndex],
         ] = [
            arr[rowIndex][columnIndex],
            arr[rowIndex][arr.length - columnIndex - 1],
         ];
      }
   }
};
rotateArray(arr);
console.log(arr);

출력

다음은 콘솔의 출력입니다 -

[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]