프로그래머스 LEVEL 1(소수 만들기)

-
사용 언어 : javascript
-
해결 날짜 : 2022-08-08
-
해결 방법 :
- 조합을 통해 배열에 있는 숫자 중 3개씩 선택하여 반환
- 조합 계산 시 고정된 값 이후의 인덱스를 계산하여 합침
- 3개씩 선택된 값을 reduce를 통해 더한 다음 소수인지 판별
-
코드
const isPrimeNumber = (n) => {
if(n == 1) return false;
for(let i = 2; i < n; i++){
if(n % i == 0) return false;
}
return true;
}
const getCombinations = (array, num) => {
const results = [];
if (num === 1) return array.map(v => [v]);
array.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;
}
function solution(nums) {
var answer = 0;
const combinations = getCombinations(nums, 3);
for(const combination of combinations) {
const result = combination.reduce(function add(sum, currValue) {
return sum + currValue;
}, 0);
if(isPrimeNumber(result)) answer++;
}
return answer;
}