본문 바로가기

알고리즘 코딩

배열에서 요소 3개를 더했을 때, 소수가 되는 경우의 개수

문제는 제목과 같고 자세한 문제는 아래에서 확인 가능하다. 

https://school.programmers.co.kr/learn/courses/30/lessons/12977

 

 

결과적으로 작성한 코드는 아래와 같다. 이중 재귀함수getCombinations 부분은 인터넷에서 그대로 가져왔다.

getCombinations의 자세한 내용은 아래 포스팅으로 정리했다.  대단히 복잡한 함수이고 이걸 만든 사람은 어떻게 만들었을지 궁금하고 그분이 존경스럽다.

https://gamunbidev.tistory.com/80

function solution(nums) {
    var answer = 0;
    const getCombinations = (arr, num) => {
      const results = [];
      if (num === 1) return arr.map(v => [v]);
    
      arr.forEach((fixed, index, origin) => {
        const rest = origin.slice(index + 1);
        const combinations = getCombinations(rest, num - 1);
        const attached = combinations.map(v => [fixed, ...v]);
        results.push(...attached);
    
      });
      return results;
    }

    const isPrime = (num) => {  
      if(num === 2) {
        return true;
      }    
      for(let i = 2; i <= Math.floor(Math.sqrt(num)); i++){
        if(num % i === 0){
          return false; 
        }
      }
      return true; 
    } 
    let added = getCombinations(nums, 3).map((v) => v.reduce((acc, cur)=>{ return acc + cur }) )

    let SosuNum = added.filter((v)=>{ return isPrime(v)}).length
    answer = SosuNum
    return answer;
}