PR - 소수 만들기

Goody·2021년 3월 14일
0

알고리즘

목록 보기
67/122

문제

주어진 숫자 중 3개의 수를 더했을 때 소수가 되는 경우의 개수를 구하려고 합니다. 숫자들이 들어있는 배열 nums가 매개변수로 주어질 때, nums에 있는 숫자들 중 서로 다른 3개를 골라 더했을 때 소수가 되는 경우의 개수를 return 하도록 solution 함수를 완성해주세요.


예시

numsresult
[1,2,3,4]1
[1,2,7,6,4]4

풀이

  • 주어진 배열 nums 의 원소 3개를 갖는 모든 경우의 수를 구한다.
  • 모든 경우의 수의 배열들이 들어있는 배열의 원소끼리 합하게 한다.
  • 합해진 원소가 소수인지 검사한다.

코드

function solution(nums) {
 
    const combinations = getCombinations(nums, 3);
    const sumArr = combinations.map((el) => {
        return el.reduce((acc,cur) => acc += cur);
    })
    const answerArr = sumArr.filter((el) => isPrime(el));
    
    return answerArr.length;
}


function getCombinations(arr,selectNumber) {
    const results = [];
    if (selectNumber === 1) return arr.map((value) => [value]);

    arr.forEach((fixed, index, origin) => {
        const rest = origin.slice(index+1); 
        const combinations = getCombinations(rest, selectNumber - 1);
        const attached = combinations.map((combination) => [fixed, ...combination]);
        results.push(...attached);
    });
  
    return results;
}


function isPrime(n) {
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) return false;
    }

    return true; 
}

0개의 댓글