본문 바로가기

알고리즘&코테

[알고리즘] 배열 회전

1차원 배열 회전

function rotate(array, step = 0) {
  if (step == 0) return [...array];

  let temp;
  let stepped;

  if (step > 0) { // 시계(우측) 방향 회전
    stepped = array.length - step;
    temp = array.slice(0, stepped);
  } else { // 반시계(좌측) 방향 회전
    stepped = Math.abs(step);
    temp = array.slice(0, stepped);
  }

  return array.slice(stepped).concat(temp);
}

const a = [1, 2, 3, 4, 5, 6];

const result = rotate(a, -1);
console.log(result);
// [6, 1, 2, 3, 4, 5]

const result2 = rotate(a, 2);
console.log(result2);
// [5, 6, 1, 2, 3, 4]

console.log(a);
// [1, 2, 3, 4, 5, 6]

 

 

2차원 배열 회전

// 회전하고 싶은 2차원 배열 array
// 회전 수 step

function rotate(array, step = 0) {
  if (step == 0) return array;
  
  const N = array.length;
  const M = array[0].length;
  const result = Array(M)
    .fill()
    .map((el) => Array(N).fill(0));

  while (step % 4) {
    result.forEach((rows, i) =>
      rows.forEach((col, j) => {
        if (step < 0) {
          result[i][j] = array[j][M - i - 1];
        } else {
          result[i][j] = array[N - j - 1][i];
        }
      })
    );
    if (step < 0) {
      step++;
    } else {
      step--;
    }
  }

  return result;
}

 

2차원 배열 대칭

function symmetry(array) {
  const [N, M] = [array[0].length, array.length];
  const result = Array(N).fill().map(el=>Array(M).fill(0));
  
  for(let i = 0; i < N; i++) {
    for(let j = 0; j < M; j++) {
      result[i][j] = array[j][i];
    }
  }
  
  return result;
}

const a = [[1,2,3],[4,5,6],[7,8,9]];
const result = symmetry(a);

console.log(result);
// [[1,4,7],[2,5,8],[3,6,9]]