https://school.programmers.co.kr/learn/courses/30/lessons/42890
// 조합
const getCombination = (elements, pick) => {
if (pick === 1) return elements.map((elem) => [elem]);
const combinations = [];
elements.forEach((element, index) => {
const smallerCombinations = getCombination(elements.slice(index + 1), pick - 1);
smallerCombinations.forEach((combination) => combinations.push([element].concat(combination)));
});
return combinations;
};
// 유일성 체크
const uniqueness = (relation, elements, row) => {
const arr = new Array(row).fill("");
elements.forEach((attr) => {
for (let tuple = 0; tuple < row; ++tuple)
arr[tuple] += relation[tuple][attr];
});
return !arr.some((x) => arr.indexOf(x) !== arr.lastIndexOf(x)); // 중복체크
};
// 최소성 체크
const minimality = (answer, elements) => {
return answer.length
? answer.every((arr) => arr.filter((a) => elements.some((b) => a === b)).length !== arr.length)
: true;
};
function solution(relation) {
const answer = [];
const [attribute, row, column] = [Array.from({ length: relation[0].length }, (_, idx) => idx), relation.length, relation[0].length];
for (let i = 1; i <= column; ++i) {
const combinations = getCombination(attribute, i); // '조합'으로 경우의 수를 만든다.
combinations.forEach((elements) => {
if (uniqueness(relation, elements, row) && minimality(answer, elements)) // 유일성 & 최소성 체크
answer.push(elements);
});
}
return answer.length;
}
'Coding Test > Programmers' 카테고리의 다른 글
[Programmers] (그리디 or 완전탐색) Lv 2. 마법의 엘리베이터 (0) | 2023.03.31 |
---|---|
[Programmers] Lv 0. 옹알이 (0) | 2023.03.28 |
[Programmers] (재귀) Lv 2. 하노이의 탑 (0) | 2023.03.28 |
[Programmers] Lv 2. 무인도 여행 (0) | 2023.03.28 |
[Programmers] (2020 KAKAO BLIND RECRUITMENT) Lv 2. 문자열 압축 (0) | 2023.03.26 |
댓글