[JavaScript] 프로그래머스 메뉴 리뉴얼 LEVEL2
11849 단어 JavaScript조합프로그래머스JavaScript
const getCombinations = (arr, selectNumber) => {
const results = [];
if (selectNumber === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, selectNumber - 1);
const attached = combinations.map((combination) => [fixed, ...combination]);
results.push(...attached);
});
return results;
}
function solution(orders, course) {
const answer = [];
const obj = {};
for (const order of orders) {
const orderArr = order.split('');
let combiArr = [];
for (const c of course) {
if (order.length < c) break;
const combi = getCombinations(orderArr, c);
combiArr = combiArr.concat(combi);
}
for (const combi of combiArr) {
const str = combi.sort().join('');
obj[str] ? obj[str] += 1 : obj[str] = 1;
}
}
for (const c of course) {
const filteredArr = Object.entries(obj).filter(o => o[0].length === c && o[1] > 1);
const max = Math.max(...filteredArr.map(f => f[1]));
filteredArr.forEach(f => {
if (f[1] === max) answer.push(f[0]);
});
}
return answer.sort();
}
풀이
뽀인트는 각 order에 대해 조합을 만드는 것이다!
가능한 모든 조합을 만들었다면, 그 조합의 개수를 새는 것이다.
주의할 점은 조합을 알파벳 순서로 정렬해줘야 'XW'랑 'WX'랑 같은 걸로 칠 수 있다.
각 조합별로 갯수를 셌다면, 최종적으로 course랑 문자열의 길이가 같은 조합 중 갯수가 가장 많은 조합을 answer에 추가해주면 된다.
Author And Source
이 문제에 관하여([JavaScript] 프로그래머스 메뉴 리뉴얼 LEVEL2), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@johnyejin/JavaScript-프로그래머스-메뉴-리뉴얼-LEVEL2저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)