코딩테스트를 위한 자료구조 알고리즘/코드조각

코드 스니펫

테오구 2021. 12. 14. 21:33
728x90

첫 글자가 대문자인 문자열 만들기

let strSplit = str.split(' ');
  for(let i = 0; i < strSplit.length; i++){
    strSplit[i] = strSplit[i].charAt(0).toUpperCase() + strSplit[i].slice(1);
  }

2차원 배열을 객체로 만들기

let result = {}
  for(let i = 0; i < arr.length; i++){
    if (arr[i].length > 0 && result[arr[i][0]] === undefined){
    result[arr[i][0]] = arr[i][1];
    }
  }
  return result;

오름차순 정렬

let sorted = stuff.sort((a,b) => a-b)
//0, 50, 80, 50] 가 [50, 50, 70, 80]

그리디 알고리즘

function greedy(stuff, limit) {
  // 오름차순 정렬 [70, 50, 80, 50] 가 [50, 50, 70, 80]된다.
  // 하나하나 나르는 경우의수
  let sorted = stuff.sort((a,b) => a-b)
  // 2개이상의 물건을 담는 박스의 수를 담는 변수
  let count = 0
  
  // 가장 무거운 짐
  let lastIdx = sorted.length - 1
  // 가장 가벼운 짐
  let pivot = 0
 

  while(lastIdx > pivot){
    if(sorted[pivot] + sorted[lastIdx] <= limit){
      count++ 
      pivot++ 
      lastIdx-- 
    }else{
      lastIdx-- 
    }
  }
  return stuff.length - count
}

 

보드 게임 유효성 검사

const isValid = (y, x) => 0 <= y && y < board.length && 0 <= x && x < board.length;

 

길이 n만큼의 배열 만들기

 let dp = Array(target + 1).fill(0);

 

순열

function permutation(arr, selectNum) {
  let result = [];
  if (selectNum === 1) return arr.map((v) => [v]);

  arr.forEach((v, idx, arr) => {
    const fixer = v;
    const restArr = arr.filter((_, index) => index !== idx);
    const permuationArr = permutation(restArr, selectNum - 1);
    const combineFixer = permuationArr.map((v) => [fixer, ...v]);
    result.push(...combineFixer);
  });
  return result;
}

 

조합

function combination(arr, selectNum) {
  const result = [];
  if (selectNum === 1) return arr.map((v) => [v]);
  arr.forEach((v, idx, arr) => {
    const fixed = v;
    const restArr = arr.slice(idx + 1);
    const combinationArr = combination(restArr, selectNum - 1);
    const combineFix = combinationArr.map((v) => [fixed, ...v]);
    result.push(...combineFix);
  });
  return result;
}

 

중복순열 코드

function permutation(arr, selectNum) {
  const result = [];
  if (selectNum === 1) return arr.map((v) => [v]);

  arr.forEach((v, idx, arr) => {
    const fixed = v;
    const restArr = arr;
    const permutationArr = permutation(restArr, selectNum - 1);
    const combineFix = permutationArr.map((v) => [fixed, ...v]);
    result.push(...combineFix);
  });
  return result;
}

 

멱집합

function powerSet(arr) {
  const result = [];
  function findPowerSet(currentArr, currentIndex) {
    if (currentIndex === arr.length) {
      return result.push(currentArr);
    }
  
    findPowerSet(currentArr.concat(arr[currentIndex]), currentIndex + 1);
    findPowerSet(currentArr, currentIndex + 1);
  }
  findPowerSet([], 0);
  return result;
}
728x90