|
| 1 | +package programmers.level2.week_27; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashSet; |
| 5 | + |
| 6 | +/** |
| 7 | + * 후보키 |
| 8 | + * https://programmers.co.kr/learn/courses/30/lessons/42890?language=java |
| 9 | + */ |
| 10 | +public class Solution003 { |
| 11 | + ArrayList<HashSet<Integer>> candidateKey; |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + String[][] relation = {{"100", "ryan", "music", "2"}, {"200", "apeach", "math", "2"}, {"300", "tube", "computer", "3"}, {"400", "con", "computer", "4"}, {"500", "muzi", "music", "3"}, {"600", "apeach", "music", "2"}}; |
| 15 | + Solution003 sol = new Solution003(); |
| 16 | + System.out.println(sol.solution(relation)); |
| 17 | + } |
| 18 | + |
| 19 | + public int solution(String[][] relation) { |
| 20 | + candidateKey = new ArrayList<>(); |
| 21 | + int colSize = relation[0].length; |
| 22 | + |
| 23 | + for (int i = 1; i <= colSize; ++i) { |
| 24 | + makeKeySet(-1, colSize - 1, 0, i, new HashSet<>(), relation); |
| 25 | + } |
| 26 | + |
| 27 | + return candidateKey.size(); |
| 28 | + } |
| 29 | + |
| 30 | + private void makeKeySet(int attr, int maxAttr, int idx, int size, HashSet<Integer> keySet, String[][] relation) { |
| 31 | + if (idx == size) { |
| 32 | + for (HashSet<Integer> key : candidateKey) if (keySet.containsAll(key)) return; |
| 33 | + if (isUnique(keySet, relation)) candidateKey.add(keySet); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + for (int i = attr + 1; i <= maxAttr; ++i) { |
| 38 | + HashSet<Integer> newKeySet = new HashSet<>(keySet); |
| 39 | + newKeySet.add(i); |
| 40 | + makeKeySet(i, maxAttr, idx + 1, size, newKeySet, relation); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + private boolean isUnique(HashSet<Integer> keySet, String[][] relation) { |
| 45 | + HashSet<String> set = new HashSet<>(); |
| 46 | + for (String[] row : relation) { |
| 47 | + StringBuilder key = new StringBuilder(); |
| 48 | + |
| 49 | + for (int col : keySet) { |
| 50 | + key.append(row[col]); |
| 51 | + } |
| 52 | + |
| 53 | + if (set.contains(key.toString())) return false; |
| 54 | + |
| 55 | + set.add(key.toString()); |
| 56 | + } |
| 57 | + return true; |
| 58 | + } |
| 59 | +} |
0 commit comments