자바스크립트 - 조합, 수열

Urther·2022년 3월 23일
0

조합

const getCombinations = (arr, selectNum) => {
  const result = [];

  if (selectNum === 1) return arr.map((element) => [element]);

  arr.forEach((fixed, index, origin) => {
    const rest = origin.slice(index + 1);
    const combinations = getCombinations(rest, selectNum - 1);
    const attached = combinations.map((element) => [fixed, ...element]);

    result.push(...attached);
  });

  return result;
};

순열

const getPermutations = function (arr, selectNumber) {
  const results = [];
  if (selectNumber === 1) return arr.map((el) => [el]);

  arr.forEach((fixed, index, origin) => {
    const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
    // fixed 를 제외한 모든 부분을 붙여준다.
    const permutations = getPermutations(rest, selectNumber - 1);
    const attached = permutations.map((el) => [fixed, ...el]);

    results.push(...attached);
  });


  return results;
};

순열은 순서 상관 있음.

90 도 회전

시계방향

const rotate90Degree = (box) => {
  const rowLen = box[0].length;
  const colLen = box.length;

  // y 축 고정 먼저 돌려주기
  let clockNow = colLen - 1;
  const result = Array.from(Array(rowLen), () => []);

  // 시계방향
  for (let i = 0; i < colLen; i++) {
    for (let j = 0; j < rowLen; j++) {
      result[j][clockNow] = box[i][j];
    }
    clockNow--;
  }
  return result;
};

반시계방향

const rotate90Degree = (box) => {
  const rowLen = box[0].length;
  const colLen = box.length;

  // y 축 고정 먼저 돌려주기
  let clockNow = 0;
  const result = Array.from(Array(rowLen), () => []);

  for (let i = 0; i < colLen; i++) {
    for (let j = 0; j < rowLen; j++) {
      result[rowLen - 1 - j][clockNow] = box[i][j];
    }
    clockNow++;
  }

  return result;
};
profile
이전해요 ☘️ https://mei-zy.tistory.com

0개의 댓글