Level
프로그래머스 Lv2
Day
11일
kakao
2019 카카오 블라인드
 
function solution(relation) {
    var answer = 0;
    const totalAttribute = relation[0].length;
    const minimality = [];
    
    const isMinimal = (node) => {
        if(minimality.some(candidateKey => candidateKey.every(val => node.indexOf(val)!==-1))){
            return false;
        };

        minimality.push(node);
        return true;
    }

    const isUnique = (node) => { // @param arr
        const obj = {};

        relation.forEach(row => {            
            const key = node.reduce((acc, each) => acc+','+row[each], '');          
            obj[key] = obj[key] ? obj[key]+1 : 1;
        })        

        for(const key in obj){
            if(obj[key] > 1){
                return false;
            }
        }

        return true;
    }

    const stack = [];
    let i=0;
    while(i<totalAttribute){
        stack.push([i]);
        i++;
    }

    while(stack.length){
        const node = stack.shift();

        if(isUnique(node)){
            if(isMinimal(node)){
                answer++;
            }
        }else{
          let next = node[node.length-1] + 1;          
          while(next<totalAttribute){
            stack.push([...node, next]);
            next++;
          }
        }
    }

    return answer;
}