[ALGO] 프로그래머스 - 뉴스 클러스터링(자바스크립트, javascript)

프로그래머스 - 뉴스 클러스터링

풀이

function solution(str1, str2) {
    var answer = 0;
    
    str1 = str1.toUpperCase();
    str2 = str2.toUpperCase();
    
    function splitStr(str) {
        let obj = {};
        let arr = [];
        let reg = /^[a-zA-Z]*$/;
        for (let i = 0; i < str.length - 1; i++) {
            if (reg.test(str[i]) && reg.test(str[i+1])) {
                const tmpStr = str[i] + str[i + 1];
                arr.push(tmpStr);
            }
        }
        return arr;
    }
    
    let A = splitStr(str1);
    let B = splitStr(str2);
    
    let set = new Set([...A, ...B]);
    
    let gyo = 0;
    let hap = 0;
    
    if (A.length === 0 && B.length === 0) {
        return 65536;
    }
    set.forEach(i => {
        const la = A.filter(item => item === i).length;
        const lb = B.filter(item => item === i).length;
        
        if (la === lb) {
            gyo += la;
            hap += la;
        }
        else {
            gyo += Math.min(la, lb);
            hap += Math.max(la, lb);
        }
    });
    return Math.floor((gyo / hap) * 65536);
    
}
  • 211025 다시 품
function solution(str1, str2) {    
    // 대문자로 변경
    str1 = str1.toUpperCase();
    str2 = str2.toUpperCase();
    
    // 다중집합
    const regExp = /^[a-zA-Z]*$/;
    function multiSet(str) {
        let map = new Map();
        for (let i = 1; i < str.length; i++) {
            const key = `${str[i - 1]}${str[i]}`;
            if (regExp.test(key)) {
                if (map.has(key)) {
                    map.set(key, map.get(key) + 1);
                } else map.set(key, 1);
            }
        }
        return map;
    }
    
    const set1 = multiSet(str1);
    const set2 = multiSet(str2);
    
    if (set1.size === 0 && set2.size === 0) return 65536;
    
    // 교집합 개수
    let intersaction = 0;
    set1.forEach((v, k) => {        
        if (set2.has(k)) {
            intersaction += Math.min(v, set2.get(k));
        }
    });
    
    // 합집합 개수
    let union = 0;
    set1.forEach((v, k) => {
        if (set2.has(k)) {
            union += Math.max(v, set2.get(k));
        } else union += v;
    });
    
    set2.forEach((v, k) => {
        if (!set1.has(k)) union += v;
    });
    
    return parseInt((intersaction / union) * 65536);
}

좋은 웹페이지 즐겨찾기