본문 바로가기

프로그래머스/해시

[해시] 프로그래머스 '할인 행사' - js

반응형

1. 문제

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

 

프로그래머스

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

programmers.co.kr

2. 코드

처음 풀었던 코드)

왜 4,12번만 통과인지 이해가 안된다....내가 어딜 잘못했는지 알고싶드아아아아악!!!!

function solution(want, number, discount) {
    let answer = 0;
    let total = number.reduce((a,c) => a+=c);
    let right = true;
    
    for(let i=0;i<discount.length-10;i++){
        let temp = discount.slice(i,i+10);
        let tempNum = number.slice();
        right = true;
        for(let j=0;j<temp.length;j++){
            if(want.includes(temp[j])) tempNum[want.indexOf(temp[j])]--;
            else if(!want.includes(temp[j]) || tempNum[want.indexOf(temp[j]) === 0]) {
                right = false;
                break;
            }
        }
        if(right){
            if(tempNum.reduce((a,c) => a+=c) === 0) answer++;
        }

    }
    
    return answer;
}

정답 코드)

같은 유형의 요소들을 지지고볶아 줄 때는 해시맵!! 아차!! 이걸 잊다니... 이 문제는 해시 맵으로 풀면 아주아주 쉬웠던 문제였다.

function solution(want, number, discount) {
  let answer = 0;
  
  // 할인 품목과 원하는 제품이 일치하는지 확인하는 함수
  const isMatch = (arr) => { 
      let map = new Map();   // 매번 map을 초기화
      arr.forEach(el => map.set(el,(map.get(el)||0)+1)); // 할인 품목들을 map에 셋팅
      for(let i = 0; i < want.length; i++){
          // 원하는 품목의 수량과 할인 품목이 일치하지 않으면 false
          if(map.get(want[i]) !== number[i]) return false;
      }             
      return true;  
  }
  
  for(let j = 0; j <= discount.length - 10; j++){
      let arr = discount.slice(j, j+10);
      if(isMatch(arr)){
          answer++;
      } 
  }
    return answer;
}

 

그래도 아직까지 내가 푼 방식이 왜 틀렸는지 이해가 안된다...예제 테케는 다 되는데... 다시 봐도 이해가 안되네...

복기

5/29
반응형