일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- Jest
- tailwind
- 반공변성
- 무한 스크롤
- RTK Query
- React
- webpack
- map
- 리터럴 타입
- ESlint
- 태그된 유니온
- useAppDispatch
- 타입 좁히기
- async/await
- recoil
- 공변성
- 결정 알고리즘
- 이분 검색
- 호이스팅
- 인터섹션
- app router
- dfs
- Promise
- Cypress
- TS
- CI/CD
- 투포인터
- SSR
- autosize
- CORS
- Today
- Total
짧은코딩
프로그래머스) 메뉴 리뉴얼(조합) 본문
-문제 사이트
https://school.programmers.co.kr/learn/courses/30/lessons/72411
코드
function solution(orders, course) {
let answer = [];
course.map((num) => {
const map = new Map();
orders.map((order) => {
const all = getCombination(order.split("").sort(), num);
all.map((cons) => {
const con = cons.join("");
map.set(con, map.has(con) ? map.get(con) + 1 : 1);
});
});
const maxNum = Math.max(...map.values());
map.forEach((value, menu) => {
if (value === maxNum && value >= 2) answer.push(menu);
});
});
return answer.sort();
}
function getCombination(arr, num) {
const result = [];
if (num === 1) return arr.map((v) => [v]);
arr.forEach((value, index, origin) => {
const rest = origin.slice(index + 1);
const combination = getCombination(rest, num - 1);
const attach = combination.map((v) => [value, ...v]);
result.push(...attach);
});
return result;
}
해결 방법
이 문제는 종합 문제라고 생각한다. 이 문제에서 조합(combination), map, forEach의 개념을 확실하게 알지 못하면 이 문제를 풀 수 없기 때문이다. 그리고 문제를 이해하는데 있어서 실수한 점은 course의 개수 만큼 만들어진 코스 요리 중에서 2번 이상 주문 받고 가장 많이 주문된 코스 요리만 최종 결과에 추가해주면 된다는 점이다.
getCombination
function getCombination(arr, num) {
const result = [];
if (num === 1) return arr.map((v) => [v]);
arr.forEach((value, index, origin) => {
const rest = origin.slice(index + 1);
const combination = getCombination(rest, num - 1);
const attach = combination.map((v) => [value, ...v]);
result.push(...attach);
});
return result;
}
이 문제를 풀기 위해서 가장 먼저 이해해야 할 점이 조합이라고 생각한다. 그리고 내가 몰랐던 부분은 forEach를 하면 매개변수에 (값, 인덱스 위치, 원본 배열)이라는 점을 몰라서 반성을 많이 했다.
만약 getCombination(["a", "b", "c"], 2)로 한다면 맨 처음 rest = ["b", "c"]이며 combination은 재귀 함수를 통해 [["b"], ["c"]]가 될 것이다. 따라서 attach는 ["a", "b"], ["a", "c"]가 되며 result에 스프레드 연산자를 이용해서 push해주면 된다. 이런식으로 반복하면 조합을 구할 수 있다.
solution
function solution(orders, course) {
let answer = [];
course.map((num) => {
const map = new Map();
orders.map((order) => {
const all = getCombination(order.split("").sort(), num);
all.map((cons) => {
const con = cons.join("");
map.set(con, map.has(con) ? map.get(con) + 1 : 1);
});
});
const maxNum = Math.max(...map.values());
map.forEach((value, menu) => {
if (value === maxNum && value >= 2) answer.push(menu);
});
});
return answer.sort();
}
solution에서는 course만큼 반복을한다. 그 과정에서 orders 안에 있는 주문 내역들을 course 수 만큼 조합으로 구한다. map에 그 요리의 조합이 나온 횟수를 저장한다.
그리고 maxNum에는 map의 value 중 가장 큰 값을 저장한다. 이때 map의 모든 value 중 가장 큰 값을 구하기 위해서는 Math.max(...map.values())를 하면된다. map을 순회하면서 value가 maxNum이랑 같고 2이상이면 answer에 추가해준다.
최종적으로 answer를 정렬해서 반환해주면 정답이 나온다.
'코딩 테스트(Python) > 백준, 프로그래머스' 카테고리의 다른 글
1753 최단경로 (0) | 2022.07.07 |
---|---|
1931 회의실 배정 (0) | 2022.06.29 |
9095 1, 2, 3 더하기 (0) | 2022.06.26 |
17219 비밀번호 찾기 (0) | 2022.06.25 |
1로 만들기(백준) (0) | 2022.06.22 |