-
프로그래머스 / 광물 캐기코딩 테스트/Level 2 2023. 3. 24. 15:21반응형
https://school.programmers.co.kr/learn/courses/30/lessons/172927
파이썬
제안사항을 확인하니 재귀를 이용해도 될 정도
def solution(picks, minerals): def solve(picks, minerals, fatigue): if sum(picks) == 0 or len(minerals) == 0: return fatigue result1 = result2 = result3 = float('inf') if picks[0] > 0: fatigues = {"diamond": 1, "iron": 1, "stone": 1} next_fatigue = sum(fatigues[mineral] for mineral in minerals[:5]) result1 = solve([picks[0] - 1, picks[1], picks[2]], minerals[5:], fatigue + next_fatigue) if picks[1] > 0: fatigues = {"diamond": 5, "iron": 1, "stone": 1} next_fatigue = sum(fatigues[mineral] for mineral in minerals[:5]) result2 = solve([picks[0], picks[1] - 1, picks[2]], minerals[5:], fatigue + next_fatigue) if picks[2] > 0: fatigues = {"diamond": 25, "iron": 5, "stone": 1} next_fatigue = sum(fatigues[mineral] for mineral in minerals[:5]) result3 = solve([picks[0], picks[1], picks[2] - 1], minerals[5:], fatigue + next_fatigue) return min(result1, result2, result3) return solve(picks, minerals, 0)
이 정도면 깔끔
def solution(picks, minerals): def solve(picks, minerals, fatigue): if sum(picks) == 0 or len(minerals) == 0: return fatigue result = [float('inf')] for i, fatigues in enumerate(({"diamond": 1, "iron": 1, "stone": 1}, {"diamond": 5, "iron": 1, "stone": 1}, {"diamond": 25, "iron": 5, "stone": 1},)): if picks[i] > 0: next_picks = picks.copy() next_picks[i] -= 1 next_fatigue = fatigue + sum(fatigues[mineral] for mineral in minerals[:5]) result.append(solve(next_picks, minerals[5:], next_fatigue)) return min(result) return solve(picks, minerals, 0)
굳이 이 정도는....
def solution(picks, minerals, fatigue=0): def get_next_picks(now_picks, i): next_picks = now_picks.copy() next_picks[i] -= 1 return next_picks if sum(picks) == 0 or len(minerals) == 0: return fatigue return min([ solution(get_next_picks(picks, i), minerals[5:], fatigue + sum(fatigues[mineral] for mineral in minerals[:5])) if picks[i] > 0 else float('inf') for i, fatigues in enumerate(({"diamond": 1, "iron": 1, "stone": 1}, {"diamond": 5, "iron": 1, "stone": 1}, {"diamond": 25, "iron": 5, "stone": 1}))])
코틀린
class Solution { private fun solve(picks: IntArray, minerals: List<String>, fatigue: Int): Int { if (picks.sum() == 0 || minerals.isEmpty()) return fatigue return listOf( mapOf("diamond" to 1, "iron" to 1, "stone" to 1), mapOf("diamond" to 5, "iron" to 1, "stone" to 1), mapOf("diamond" to 25, "iron" to 5, "stone" to 1), ).mapIndexed { index, fatigues -> if (picks[index] > 0) { val nextPicks = picks.clone() nextPicks[index] -= 1 solve(nextPicks, minerals.drop(5), fatigue + minerals.take(5).sumOf { fatigues.getOrDefault(it, 0) }) } else 2147483647 }.minOrNull()!! } fun solution(picks: IntArray, minerals: Array<String>): Int { return solve(picks, minerals.asList(), 0) } }
반응형