프로그래머스 LEVEL 2(메뉴 리뉴얼)
-
사용 언어 : javascript
-
해결 날짜 : 2022-09-06
-
해결 방법 :
- orders를 돌며 각 order를 사전순으로 정렬
- 각 order에 대한 조합을 돌며 course 별 최대 주문 개수 저장
- 최대 주문 개수에 대한 order를 answer에 담아 중복 제거 후 사전 순으로 정렬
-
회고 : -
-
코드
const getCombinations = (arr, num) => { const results = []; if (num === 1) return arr.map(v => [v]); arr.forEach((fixed, index, origin) => { const rest = origin.slice(index + 1); const combinations = getCombinations(rest, num - 1); const attached = combinations.map(v => [fixed, ...v]); results.push(...attached); }); return results; } const sortString = (str) => { return str.split('').sort().join(''); } function solution(orders, course) { var answer = []; const allCombinations = []; const maxOrder = {}; for (const count of course) { maxOrder[count] = 0; } const sortedOrders = []; for (const order of orders) { sortedOrders.push(sortString(order)); } for (const order of sortedOrders) { for (const count of course) { for (const combination of getCombinations(order.split(''), count)) { allCombinations.push(combination.join('')); } } } for (const combination of allCombinations) { const length = allCombinations.filter((c) => c === combination).length; if (length > 1) { if (length >= maxOrder[combination.length]) { maxOrder[combination.length] = length; } } } for (const combination of allCombinations) { const length = allCombinations.filter((c) => c === combination).length; if (maxOrder[combination.length] === length) { answer.push(combination); } } return [...new Set(answer)].sort(); }
-
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges