코딩테스트 풀이

프로그래머스 코딩테스트 - 광물 캐기

hanlabong 2024. 11. 10. 21:31
728x90

문제 설명

 

제한 사항

 

해결 방법

아이디어

  • 광물을 5개씩 쪼개서 저장 => 한 번 곡갱이를 선택하면 5개를 쪼개야 함
    • 주어진 곡갱이로 쪼갤 수 있을 만큼의 광물만 저장
  • 광물 정렬
    • 강한 곡갱이일 수록 강한 광물이 많은 조합에 사용하는 것이 좋음
    • 다이아몬드 -> 철 -> 돌 순서대로 정렬
  • 다이아몬드 -> 철 -> 돌 곡갱이 순서대로 광물 조합에 사용

코드

const PICK = ["diamond", "iron", "stone"];
const FATIGUE = {diamond: [1, 1, 1], iron: [5, 1, 1], stone: [25, 5, 1]}

function solution(picks, minerals) {
    var answer = 0;
    const count = picks.map((p, idx) => Array(p).fill(PICK[idx])).flat()
    const mineList = []
    for(let i = 0 ;i < minerals.length ; i += 5) {
        mineList.push(minerals.slice(i, i + 5))
        if (mineList.length === count.length) {
            i = minerals.length
        }
    }
    mineList
        .sort((a, b) => a.filter(c => c === "iron").length > b.filter(c => c === "iron").length ? -1 : 1)
        .sort((a, b) => a.filter(c => c === "diamond").length > b.filter(c => c === "diamond").length ? -1 : 1)
    
    while(mineList.length) {
        const item = mineList.shift();
        const pick = count.shift();
        
        const fatigue = FATIGUE[pick];
        PICK.forEach((p, idx) => {
            answer += item.filter((c) => c === p).length * fatigue[idx]
        })
    }
    
    return answer;
}

 

결과

728x90