문제는 제목과 같고 자세한 문제는 아래에서 확인 가능하다.
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;
}
'알고리즘 코딩' 카테고리의 다른 글
재귀함수. 집요한 정리 (0) | 2023.04.22 |
---|---|
배열에서 문자열 요소들을 오름차순 정렬하면 대문자부터 나온다. (0) | 2023.04.21 |
같은 숫자는 싫어 ! 알고리즘 (0) | 2023.04.18 |
최소직사각형 알고리즘 feat. apply() 메서드 (0) | 2023.04.18 |
자연수가 하샤드 수인지 판별하는 알고리즘 (0) | 2023.04.18 |