티스토리 뷰

코딩테스트

프로그래머스 2단계 답지1

안양사람 2020. 12. 29. 01:20
728x90
SMALL

다리를 지나는 트럭 -- 이렇게 푸는게 맞나.. 싶다.

function solution(bridge_length, weight, truck_weights) {
    let truck_ing=[];
    let time=0;
    while(truck_weights.length>0){
        truck_ing.map(i=>i[1]++);
        truck_ing.length>0 && truck_ing[0][1]===bridge_length && truck_ing.shift();
        truck_ing.reduce((acc,cur) => acc+cur[0],0)+truck_weights[0]<=weight 
        && truck_ing.length<bridge_length 
        && truck_ing.push([truck_weights.shift(),0]);
        time++;
    }
    return time+bridge_length;
}

programmers.co.kr/learn/courses/30/lessons/42583

 

프린터

function solution(priorities, location) {
    const obj=priorities.map((value,index) => ({index, value}));
    let i=1;
    while(true){
        const max=Math.max.apply(null,obj.map(o => o.value));
        if(obj[0].value===max){
            if(obj[0].index===location){
                return i;
            }
            obj.shift();
            i++;
        }else{
            obj.push(obj.shift());
        }
    }
}

programmers.co.kr/learn/courses/30/lessons/42587

 

124 나라의 숫자

function solution(n) {
    let arr=[4,1,2];
    let index;
    let result="";
    while(n>0){
        index=n%3;
        n=Math.floor((n-1)/3);
        result=arr[index]+result;
    }
    return result;
}

programmers.co.kr/learn/courses/30/lessons/12899

 

기능 개발

function solution(progresses, speeds) {
    let result=[];
    let last_need_day=0;
    for(let i=0;i<progresses.length;i++){
        const need_day=Math.ceil((100-progresses[i])/speeds[i]);
        if(need_day>last_need_day){
            result.push(1);
            last_need_day=need_day
        }else{
            result[result.length-1]++;
        }
    }
    return result;
}

programmers.co.kr/learn/courses/30/lessons/42586

 

큰 수 만들기 -- 내가 멍청한가... 이걸 어떻게 생각해낸거지

function solution(number, k) {
    const answer = [];
    let head = 0;
    let del = k;
    while(head < number.length) {
        if(del && answer[answer.length-1] < number[head]) {
            answer.pop();
            del--;
            continue;
        }
        answer.push(number[head++]);
    }

    return answer.slice(0, number.length - k).join('');
}

programmers.co.kr/learn/courses/30/lessons/42883

 

소수찾기 -- 순열구하는게 어렵다.. 그것만 하면 쉬움

const getPermutations = function (arr, selectNumber) {
  const results = [];
  if (selectNumber === 1) return arr.map((i) => [i]); // 1개씩 선택한다면 모든 배열의 원소를 return한다

  arr.forEach((fixed, index, array) => {
    const rest = [...array.slice(0, index), ...array.slice(index + 1)]; // fixed를 제외한 나머지 배열(순열)
    const permutations = getPermutations(rest, selectNumber - 1); // rest에 대한 순열을 구한다.
    const attached = permutations.map((permutation) => [fixed, ...permutation]); // fixed와 rest에 대한 조합을 붙인다.
    results.push(...attached); // result 배열에 push
  });

  return results;
};

function isPrime(n){
    if(n<2) return false;
    for(let i=2;i<=n/2;i++){
        if(n%i===0){
            return false;
        }
    }
    return true;
}

function solution(numbers) {
    let answer=0;
    let permutations;
    for(let i=1;i<=numbers.length;i++){
        permutations = [...new Set(
            getPermutations(numbers.split(''),i).map((i) => {
            if(i[0]!=0) return i.join('');
            else return 0;
        }))];
        for(let j=0;j<permutations.length;j++){
            isPrime(permutations[j]) && answer++;
        }
    }
    return answer;
}


programmers.co.kr/learn/courses/30/lessons/42839

 

순열 조합

ms3864.tistory.com/277

 

순열과 조합

조합먼저 코드를 이해하면 쉬움 순열 알고리즘 const getPermutations = function (arr, selectNumber) { const results = []; if (selectNumber === 1) return arr.map((i) => [i]); // 1개씩 선택한다면 모든 배..

ms3864.tistory.com

 

가장 큰 수

function solution(numbers) {
    const answer=numbers.map(i=>i+"").sort((a,b)=>(b+a)-(a+b)).join('');
    return answer[0]==='0' ? '0' : answer;
}

programmers.co.kr/learn/courses/30/lessons/42746

 

조이스틱 -- 고생해서 풀었다... 그래서 코드가 지저분 수정할 것

function solution(name) {
  let answer = 0;
  let completeChar = 0;
  let currentIdx = 0;
  let completeFront = 0,
    completeBack = 0;
  let direction = true;
  while (completeChar !== name.length) {
    //현재 커서 단어를 바꾸기
    const current_aski = name.charCodeAt(currentIdx);
    current_aski <= 78
      ? (answer += current_aski - 65)
      : (answer += 91 - current_aski);
    direction ? completeFront++ : completeBack++;
    completeChar++;
    if (completeChar === name.length) return answer;

    //다음문자가 A일때 A가 몇개인지 확인하기
    let temp = currentIdx;
    let a_length = 0;
    if (direction) {
      temp++;
      while (name.charCodeAt(temp) === 65) {
        a_length++;
        temp++;
      }
    } else {
      temp--;
      while (name.charCodeAt(temp) === 65) {
        a_length++;
        temp--;
      }
    }

    if (a_length === name.length - completeChar) break; //남은게 전부 A이면 끝

    //방향 결정
    if (a_length + 1 > completeChar) {
      direction
        ? (currentIdx = name.length - completeBack - 1)
        : (currentIdx = completeFront);
      answer += completeChar;
      direction = !direction;
    } else {
      direction ? currentIdx++ : currentIdx--;
      answer++;
    }
  }
  return answer;
}

programmers.co.kr/learn/courses/30/lessons/42860

 

H-index -- 테스트9가 좀 틀릴만한다. 배열의 개수가 1일때나 모든 배열 값들이 index+1보다 크거나 같을 때 생각

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

programmers.co.kr/learn/courses/30/lessons/42747

 

위장

function solution(clothes) {
    let obj={};
    let answer=1;
    for(let arr of clothes){
        obj[arr[1]]=(obj[arr[1]]||0)+1;
    }
    for(let key in obj){
        answer*=obj[key]+1;
    }
    return answer-1;
}

programmers.co.kr/learn/courses/30/lessons/42578

 

구명보트

function solution(people, limit) {
    let answer = 0;
    people.sort((a,b)=>a-b);
    while(people.length){
        people[0]+people[people.length-1]<=limit && people.shift();
        people.pop();
        answer++;
    }
    return answer;
}

programmers.co.kr/learn/courses/30/lessons/42885

 

타겟 넘버 -- 깊이/너비 우선 탐색(DFS/BFS)

function solution(numbers, target) {
    let answer=0;
    function dfs(index,sum){
        if(index===numbers.length){
            if(sum===target){
                answer++;
            }
            return;
        }
        dfs(index+1,sum+numbers[index]);
        dfs(index+1,sum-numbers[index]);
    }
    dfs(0,0);
    return answer;
}

programmers.co.kr/learn/courses/30/lessons/43165

 

카펫

function solution(brown, yellow) {
    const width=brown+yellow;
    for(let y_vertical=1;y_vertical<=yellow;y_vertical++){
        if(yellow%y_vertical!==0) continue;
        let y_horizontal=yellow/y_vertical;
        let horizontal=y_horizontal+2;
        if(width%(horizontal)===0){
            return [horizontal,(width)/(horizontal)];
        }
    }
}

programmers.co.kr/learn/courses/30/lessons/42842

 

가장 큰 정사각형 찾기

for문

function solution(board){
    for(let i=1;i<board.length;i++){
        for(let j=1;j<board[0].length;j++){
            if(board[i][j]>0){
                board[i][j]=Math.min(board[i-1][j-1],board[i-1][j],board[i][j-1])+1;
            }
        }
    }
    return Math.max(...board.map(i=>Math.max(...i)))**2;
}

forEach문

function solution(board){
    board.forEach((a,i)=>a.forEach((b,j)=>{
        if(i===0 || j===0) return;
        if(board[i][j]>0){
            board[i][j]=Math.min(board[i-1][j-1],board[i-1][j],board[i][j-1])+1;
        }
    }));
    return Math.max(...board.map(i=>Math.max(...i)))**2;
}

programmers.co.kr/learn/courses/30/lessons/12905

 

올바른 괄호

function solution(s){
    let bracket=0;
    for(let i=0;i<s.length;i++){
        if(bracket<0){
            return false;
        }
        s[i]==="(" ? bracket++ : bracket--;
    }
    return bracket===0;
}

programmers.co.kr/learn/courses/30/lessons/12909

 

다른 큰 숫자

function solution(n) {
    const one=n.toString(2).match(/1/g).length; 
    while(n++){
        if(n.toString(2).match(/1/g).length===one) return n;
    }
}

programmers.co.kr/learn/courses/30/lessons/12911

 

땅따먹기

function solution(land) {
    return Math.max(...land.reduce((acc,cur)=>
                                   [
        cur[0]+Math.max(acc[1],acc[2],acc[3]),
        cur[1]+Math.max(acc[0],acc[2],acc[3]),
        cur[2]+Math.max(acc[0],acc[1],acc[3]),
        cur[3]+Math.max(acc[0],acc[1],acc[2]),
        ],[0,0,0,0]));
}

programmers.co.kr/learn/courses/30/lessons/12913

 

 

숫자의 표현 -- 이거 효율성 테스트가 좀 낮음. 그래서 코드 간단하게 못했어

function solution(n) {
    let answer=0;
    let j, equal;
    for(let i=1;i<n/2;i++){
        j=i;
        equal=0;
        while(true){
            equal+=j
            if(equal>=n){
                if(equal===n){
                     answer++;
                }
                break;
            }
            j++;
        }
    }
    answer++;
    return answer;
}

programmers.co.kr/learn/courses/30/lessons/12924

 

최댓값과 최솟값

function solution(s) {
    const arr=s.split(' ');
    return Math.min(...arr)+" "+Math.max(...arr);
}

programmers.co.kr/learn/courses/30/lessons/12939

 

최솟값 만들기

function solution(A,B){
    let answer=0;
    A.sort((a,b)=>a-b);
    B.sort((a,b)=>b-a);
    for(let i=0;i<A.length;i++){
        answer+=A[i]*B[i];
    }
    return answer;
}

programmers.co.kr/learn/courses/30/lessons/12941

 

피보나치수

function solution(n){
    var answer = [];
    for(let i=0; i<=n; i++){
        i<2 ? answer.push(i) : answer.push((answer[i-1]+answer[i-2])%1234567);
    }
    return answer[n];
}

programmers.co.kr/learn/courses/30/lessons/12945

 

행렬의 곱셈 -- 간단하게 할 수도 있는데... 바로 코드 구현이 안되네

function solution(arr1, arr2) { //arr1은 a*b, arr2는 b*c 행렬
    let answer=[]
    for(let a=0;a<arr1.length;a++){
        let row=[];
        for(let c=0;c<arr2[0].length;c++){
            let value=0;
            for(let b=0;b<arr1[0].length;b++){
                value+=arr1[a][b]*arr2[b][c];
            }
            row.push(value);
        }
        answer.push(row);
    }
    return answer;
}

programmers.co.kr/learn/courses/30/lessons/12949

 

JadenCase 문자열 만들기 -- i[0]으로 하면 안된다.

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

programmers.co.kr/learn/courses/30/lessons/12951

 

N개의 최소공배수 -- 유클리드 호제법과 reduce 함수만 알면 간단히 해결

function solution(arr) {
    return arr.reduce((acc,cur)=> acc*cur/gcd(acc,cur));
}

function gcd(n1, n2) {
  return n1%n2 ? gcd(n2, n1%n2) : n2;
}
728x90
LIST
댓글
공지사항