프로그래머스 LEVEL 2(뉴스 클러스터링)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-09-04

  • 해결 방법 :

    • 인자 str1, str2에 대해 두 글자씩 끊어서 다중집합의 원소로 만듦
    • arr1, arr2의 고유 합집합 union을 돌며 각 arr1, arr2에 속한 원소의 개수를 차집합은 min, 합집합은 max를 사용하여 추가
  • 회고 : Set() 후 filter로 차집합, 합집합 원소 개수 구하는 것 생각하는데 시간이 걸림

  • 코드

    const toMultipleSet = (str) => {
        const regex = /^[a-z]*$/;
        str = str.toLowerCase();
        const arr = [];
        for (let i = 0; i < str.length - 1; i++) {
            const temp = str.substring(i, i + 2);
            if (regex.test(temp)) {
                arr.push(temp);
            }
        }
        return arr;
    }
    
    function solution(str1, str2) {
        const arr1 = toMultipleSet(str1);
        const arr2 = toMultipleSet(str2);
            
        let intersectionLength = 0, unionLength = 0;
        const union = [...new Set([...arr1, ...arr2])];
            
        for (const element of union) {
            const arr1Length = arr1.filter(e => e === element).length;
            const arr2Length = arr2.filter(e => e === element).length;
                
            intersectionLength += Math.min(arr1Length, arr2Length);
            unionLength += Math.max(arr1Length, arr2Length);
        }
            
        return unionLength === 0 ? 65536 : Math.floor(intersectionLength / unionLength * 65536);
    }
    
  • 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges