[프로그래머스 / Javascript] 뉴스 클러스터링

어제보다·2024년 7월 31일
post-thumbnail

출처: https://school.programmers.co.kr/learn/courses/30/lessons/17677

✅ 문제 설명

✅ 내 풀이 설명

  1. str1, str2에서 알파벳 두개로만 구성된 원소 판별해서 word1_arr, word2_arr에 넣기
  2. word1_arr, word2_arr에서 같은 원소 찾아서 교집합 배열 arr_same에 넣기
  3. 정답 계산해서 return

✅ 내 풀이 코드

function solution(str1, str2) {
  const alphabet = [ "a","b","c","d","e","f","g",
                    "h","i","j","k","l","m","n","o",
                    "p","q","r","s","t","u","v","w","x","y","z",
  ];

  // 공집합
  let arr_same = [];

  // 소문자 처리
  const word1 = str1.toLowerCase();
  const word2 = str2.toLowerCase();

  // 특수문자, 숫자를 빼고 알파벳으로만 구성된 원소들 담아 둘 배열
  const word1_arr = [];
  const word2_arr = [];

  // 특수문자, 숫자를 빼고 알파벳으로만 구성된 원소들 판별 과정.
  for (let i = 0; i < word1.length - 1; i++) {
    const first = word1.slice(i, i + 1);
    const second = word1.slice(i + 1, i + 2);
    if (alphabet.includes(first) && alphabet.includes(second)) {
      word1_arr.push(first + second);
    }
  }
  const word1_cnt = word1_arr.length;

  for (let i = 0; i < word2.length - 1; i++) {
    const first = word2.slice(i, i + 1);
    const second = word2.slice(i + 1, i + 2);
    if (alphabet.includes(first) && alphabet.includes(second)) {
      word2_arr.push(first + second);
    }
  }
  const word2_cnt = word2_arr.length;

  // 교집합 판별 과정.
  for (let i = 0; i < word1_arr.length; i++) {
    for (let j = 0; j < word2_arr.length; j++) {
      if (word1_arr[i] === word2_arr[j]) {
        arr_same.push(word1_arr[i]);
        word1_arr.splice(i, 1);
        word2_arr.splice(j, 1);
        i--;
        break;
      }
    }
  }

  // 공집합인 경우
  if (word1_arr.length == 0 && word2_arr.length == 0) {
    return 65536;
  }

  return Math.floor(
    (arr_same.length / (word1_cnt + word2_cnt - arr_same.length)) * 65536
  );
}
profile
똑똑해지는중...

0개의 댓글