728x90

https://school.programmers.co.kr/learn/courses/30/lessons/150368?language=javascript

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

function solution(users, emoticons) {
    let answer = [0, 0];

    function discountCombinations(discounts, numProducts) {
    
        function generateCombo(currentCombo, depth) {
            if (depth === numProducts) {
                let plus = 0, sell = 0; //플러스 가입자수, 총 판매금액 
                
                //reduce를 사용해 이모티콘 총 구매금액을 계산 
                for (let user of users) {
                    let total = emoticons.reduce((sum, price, c) => 
                        sum + (currentCombo[c] >= user[0] ? price * (1 - currentCombo                         [c] * 0.01) : 0), 0
                    );
                    //총 구매한 금액이 목표금액보다 비싼경우 구매를 취소하고 플러스 가입 
                    if (total >= user[1]) plus++;
                    else sell += total;
                }
                //그 경우의 수 마다 max값을 비교해서 최적의 결과를 answer에 넣어줌 
                if (plus > answer[0] || (plus === answer[0] && sell > answer[1])) {
                    answer = [plus, sell];
                }
                return;
            }
            //재귀
            for (let discount of discounts) {
                generateCombo([...currentCombo, discount], depth + 1);
            }
        }
        generateCombo([], 0);
        
    }

    discountCombinations([10, 20, 30, 40], emoticons.length);
    return answer;
}

 

재귀함수를 사용해서 각 이모티콘별로 할인되는 모든 경우의 수를 구하고, 그 경우의 수 중 max 값을 찾는 

무식한 방법을 사용했다 ㅎㅎ ... 

이모티콘의 갯수가 많지 않고 할인은 10 20 30 40 단 네가지의 경우의 수만 존재하기때문에 가능했던 풀이 

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/176962#qna

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

function solution(plans) {
  var answer = [];
  var notFinish = [];

  let plan = plans.sort((a, b) => {
    const [aHours, aMinutes] = a[1].split(':').map(Number);
    const [bHours, bMinutes] = b[1].split(':').map(Number);
    return aHours * 60 + aMinutes - (bHours * 60 + bMinutes);
  });

  for (let idx = 0; idx < plan.length; idx++) {
    const p = plan[idx];
    const [hours, minutes] = p[1].split(':').map(Number);
    const date = new Date();
    date.setHours(hours, minutes, 0, 0);

    const playTime = parseInt(p[2]) * 60 * 1000;
    date.setTime(date.getTime() + playTime);

    if (idx + 1 < plan.length) {
      const [nextHours, nextMinutes] = plan[idx + 1][1].split(':').map(Number);
      const nextDate = new Date();
      nextDate.setHours(nextHours, nextMinutes, 0, 0); 

      if (nextDate < date) {
      
        notFinish.push([p[0], (date - nextDate) / (60 * 1000)]); 
      } else {
        answer.push(p[0]);

      
        let remainingTime = (nextDate - date) / (60 * 1000); 
        while (notFinish.length > 0 && remainingTime > 0) {
          const [task, timeLeft] = notFinish.pop(); 
          if (remainingTime >= timeLeft) {
            answer.push(task);
            remainingTime -= timeLeft;
          } else {
            notFinish.push([task, timeLeft - remainingTime]);
            break;
          }
        }
      }
    } else {
      answer.push(p[0]); 

      while (notFinish.length > 0) {
        answer.push(notFinish.pop()[0]);
      }
    }
  }

  return answer;
}

조건문지옥....................... 

 

스택을 활용해서 풀면 된다 

물론 자바스크립트는 스택이나 큐를 제공하지 않기 때문에 shift push pop 을 적절히 사용해서 배열을 스택처럼 써야한다. 

 

 

오답노트 : 

 

다음 과제 시작 전에 미뤄둔 과제를 처리해줘야하는데

미뤄둔 과제 리스트중에 첫번째 과제가 40분이고 다음 과제까지 남은시간이 20분이다

그러면 20분이라도 했다고 처리해줘야 문제가 해결되는거였음

 

처음에 풀때

남은시간은 20분인데 40분짜리 과제? 절대못하죠.  이러고 넘어가버려서 절반이 오류케이스로 나왔었다 

테스트케이스에 이런경우도 같이 고려해서 넣어주면 좋겠음. 설명이 부족한 문제인듯 

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/160586

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

function solution(keymap, targets) {
    var answer = [];
    var map = new Map();
    keymap.forEach((keys) => {
    for (let idx = 0; idx < keys.length; idx++) {
      let k = keys[idx];
      if (!map.has(k)) {
        map.set(k, idx + 1);
      } else {
        if (map.get(k) > idx + 1) {
          map.set(k, idx + 1);
        }
      }
    }
  });
    
    targets.forEach((t) => {
    let ans = 0;

    for (let i = 0; i < t.length; i++) {
      if (!map.has(t[i])) {
        ans = -1;
        break;
      } else {
        ans += map.get(t[i]); 
      }
    }

    answer.push(ans); 
  });
    return answer;
}

 

keymap으로 넘어오는 값을 배열로 착각하고 forEach로 풀었더니 초반에 오류가 발생했는데

for 반복문으로 푸니까 바로 해결이 되었다 ㅎㅎ 간단한문제! 

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42576

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

function solution(participant, completion) {
    var answer = '';
    var pmap = new Map();
    var cmap = new Map();
    
    participant.map((p)=>pmap.set(p,pmap.get(p)?pmap.get(p)+1:1));
    completion.map((c)=>cmap.set(c,cmap.get(c)?cmap.get(c)+1:1));
    for (p of participant){
          if(pmap.get(p)!==cmap.get(p)){
              answer = p;
              break;
                    }
    }
    
 
    return answer;
}

 

해시를 쓸 줄 안다면 간단히 풀 수 있는 문제 

728x90

 

https://school.programmers.co.kr/learn/courses/30/lessons/1845

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

function solution(nums) {
    var max = nums.length/2;
    var ponkemon = new Map();
    for(i of nums){
        if(!ponkemon.has(i))
            ponkemon.set(i,1);
        else 
            ponkemon.set(i,ponkemon.get(i)+1);
    }
    if(ponkemon.size<max)return ponkemon.size;
    else return max;
}

해시맵으로 각 폰켓몬별 마릿수를 구하고, 

폰켓몬 / 2 값보다 폰켓몬 종류값이 큰 경우 폰켓몬 / 2 값을, 

아닐 경우 폰켓몬의 종류값을 .size로 구해서 리턴하면 된다. 

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Map

 

Map - JavaScript | MDN

Map 객체는 키-값 쌍과 키의 원래 삽입 순서를 기억합니다. 모든 값(객체 및 원시 값 모두)은 키 또는 값으로 사용될 수 있습니다.

developer.mozilla.org

자바스크립트의 해시맵을 사용할 줄 안다면 쉽게 풀 수 있는 문제다! 

 

728x90

+ Recent posts