도리쓰에러쓰

[Algorithm] 프로그래머스 코딩테스트 Level2 풀이 모음 - JavaScript 본문

Algorithm

[Algorithm] 프로그래머스 코딩테스트 Level2 풀이 모음 - JavaScript

강도리 2022. 4. 4. 18:19

프로그래머스 코딩테스트 Level2 풀이 모음입니다.

Ctrl + F 를 이용해 문제 풀이를 찾아주세요.

 

🔽 알고리즘 문제 (프로그래머스 사이트)

 

코딩테스트 연습

기초부터 차근차근, 직접 코드를 작성해 보세요.

programmers.co.kr


💡 최댓값과 최솟값

function solution(s) {
  const nums = s.split(' ').map(v => parseInt(v));
  return `${Math.min.apply(null, nums)} ${Math.max.apply(null, nums)}`;
}

 

 

💡 JadenCase 문자열 만들기

function solution(s) {
  return s.split(' ').map(v => v.charAt(0).toUpperCase() + v.slice(1).toLowerCase()).join(' ');
}

 

 

💡 다음 큰 숫자

function solution(n) {
  const oneLength = n.toString(2).split('1').length - 1;
  let temp = 0;
  do {
    n += 1;
    temp = n.toString(2).split('1').length - 1;
  } while(oneLength !== temp)
  return n;
}

 

 

💡 숫자의 표현

function solution(n) {
  let answer = 0;
  for(let i = 1; i <= n; i++) {
    if(i % 2 === 1 && n % i === 0) answer++;
  }
  return answer;
}

 

 

💡 소수 찾기

function solution(numbers) {
  let answer = [];
  const nums = numbers.split('');

  const isPrimeNum = num => {
    if(num <= 1) return false;
    for(let i = 2; i*i <= num; i++) {
      if(num % i === 0) return false;
    }
    return true;
  }
  
  const getPermutation = (arr, fixed) => {
    if(arr.length >= 1) {
      arr.map((v, i) => {
        const newNum = fixed + v;
        const copyArr = [...arr];
        copyArr.splice(i, 1);
        if(!answer.includes(+newNum) && isPrimeNum(+newNum)) answer.push(+newNum);
        getPermutation(copyArr, newNum);
      });
    }
  };

  getPermutation(nums, '');
  return answer.length;
}

 

 

💡 이진 변환 반복하기

function solution(s) {
  let count = 0, zeroRemove = 0;
  do {
    const zeroCount = s.split("0").length - 1;
    const oneCount = s.split("1").length - 1;
    count++;
    zeroRemove += zeroCount;
    s = oneCount.toString(2);
  } while(s !== "1")
  return [count, zeroRemove];
}

 

 

💡 피보나치 수

function solution(n) {
  return fib(n) % 1234567;
}

const fib = n => {
  let nums = [0, 1, 1];
  for(let i = 3; i <= n; i++) {
    nums[i] = (nums[i-1] + nums[i-2]) % 1234567;
  }
  return nums[n];
};

 

 

💡 튜플

function solution(s) {
  let answer = [];
  let sList = s.replace("{{", "").replace("}}", "").split("},{");
  let setList = [];

  sList.map(v => setList.push(v.split(",")));
  setList.sort((a, b) => {
    if(a.length > b.length) {
        return 1;
    } else {
        return -1;
    }
  });
  setList.map(v => { v.map(a => answer.push(parseInt(a))) });
  return [...new Set(answer)];
}

 

 

💡 프린터

function solution(priorities, location) {
  let max = Math.max(...priorities);
  let answer = 1;

  while(priorities.length !== 0) {
    if(priorities[0] === max) {
      if(location === 0) return answer;
      priorities.shift();
      answer++;
      max = Math.max(...priorities);
    } else {
      priorities.push(priorities.shift());
    }

    if(location !== 0) location--;
    else location = priorities.length - 1;
  }
  return -1;
}

 

 

💡 구명보트

function solution(people, limit) {
  let answer = 0;
  people.sort((a, b) => b - a);
  for(let i = 0, j = people.length - 1; i <= j; i++) {
    if(people[i] + people[j] > limit) answer++;
    else { answer++; j--; }
  }
  return answer;
}

 

 

💡 기능 개발

function solution(progresses, speeds) {
  let answer = [0];
  let days = progresses.map((v, i) => Math.ceil((100 - v) / speeds[i]));
  let maxDay = days[0];
  for(let i = 0, j = 0; i < days.length; i++) {
    if(days[i] <= maxDay) answer[j] += 1;
    else {
        maxDay = days[i];
        answer[++j] = 1;
    }
  } 
  return answer;
}

 

 

💡 파일명 정렬

function solution(files) {
  return files.sort((a, b) => {
    const aHead = a.match(/^\D+/)[0].toLowerCase();
    const bHead = b.match(/^\D+/)[0].toLowerCase();

    if(aHead < bHead) return -1;
    if(aHead > bHead) return 1;

    const aNum = a.match(/\d+/)[0].replace(/^0+/, '');
    const bNum = b.match(/\d+/)[0].replace(/^0+/, '');

    return aNum - bNum;
  });
}

 

 

💡 오픈채팅방

function solution(record) {
  const users = {};
  const arr = [];
  const stateObj = {
    Enter: '님이 들어왔습니다.',
    Leave: '님이 나갔습니다.'
  };

  record.map(v => {
    const [state, uid, name] = v.split(' ');

    if(name) users[uid] = name;
    if(state !== 'Change') arr.push([state, uid]);
  });

  return arr.map(([state, uid]) => `${users[uid]}${stateObj[state]}`);
}

 

 

💡 124 나라의 숫자

function solution(n) {
  let answer = '';
  const nums = [4, 1, 2];
  
  while(n) {
    answer = nums[n % 3] + answer;
    n = n % 3 === 0 ? n / 3 - 1 : Math.floor(n / 3);
  }
  return answer;
}

 

 

💡 짝지어 제거하기

function solution(s) {
  let stack = [];
  for(let i = 0; i < s.length; i++) {
    if(!stack.length || stack[stack.length - 1] !== s[i]) stack.push(s[i]);
    else stack.pop();
  }
  return stack.length === 0 ? 1 : 0;
}

 

 

💡 위장

function solution(clothes) {
  let answer = 1;
  let obj = {};

  clothes.map((_, i) => obj[clothes[i][1]] = (obj[clothes[i][1]] || 1) + 1);
  for(let key in obj) answer *= obj[key];
  return answer - 1;
}

 

 

💡 H-index

function solution(citations) {
  citations.sort((a, b) => b - a);
  let i = 0;
  while(i + 1 <= citations[i]) i++;
  return i;
}

 

 

💡 뉴스 클러스터링

function solution(str1, str2) {
  const splitString = str => {
    const arr = [];
    for(let i = 0; i < str.length - 1; i++) {
      const node = str.substr(i, 2);
      if(node.match(/[A-Za-z]{2}/)) {
        arr.push(node.toLowerCase());
      }
    }
    return arr;
  };

  const arr1 = splitString(str1);
  const arr2 = splitString(str2);
  const set = new Set([...arr1, ...arr2]);
  let union = 0, intersection = 0;

  set.forEach(item => {
    const has1 = arr1.filter(x => x === item).length;
    const has2 = arr2.filter(x => x === item).length;
    union += Math.max(has1, has2);
    intersection += Math.min(has1, has2);
  });
  return union === 0 ? 65536 : Math.floor(intersection / union * 65536);
}

 

 

💡 다리를 지나는 트럭

function solution(bridge_length, weight, truck_weights) {
  let bridge = Array.from({length : bridge_length}, () => 0);
  let time = 0;

  while(bridge.length) {
    bridge.shift();
    time++;

    if(truck_weights.length) {
      const sum = bridge.reduce((acc, cur) => acc + cur);
      if(sum + truck_weights[0] <= weight) bridge.push(truck_weights.shift());
      else bridge.push(0);
    }
  }
  return time;
}

 

 

💡 카펫

function solution(brown, yellow) {
  let answer = [];
  const sum = brown + yellow;

  for(let height = 3; height <= brown; height++) {
    if(sum % height === 0) {
      let weight = sum / height;
      if((height - 2) * (weight - 2) === yellow) return [weight, height];
    }
  }
  return answer;
}
Comments