728x90
https://school.programmers.co.kr/learn/courses/30/lessons/42839
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
[나의 코드]
const solution = (text) =>{
const allPossibleCases=[] // 가능한 모든 케이스
const allPossilblePrimeCases=[]// 가능한 모든 케이스 && Prime 조건 만족
//소수 판별 함수
const isPrime = (num) => {
if(num===1||num===0) return false;
if(num === 2) return true;
for(let i = 2; i <= Math.floor(Math.sqrt(num)); i++){
if(num % i === 0){
return false;
}
}
return true
}
// 순열 함수
const getPermutations = function (arr, selectNumber) {
const results = [];
if (selectNumber === 1) return arr.map((el) => [el]);
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index+1)]
const permutations = getPermutations(rest, selectNumber - 1);
const attached = permutations.map((el) => [fixed, ...el]);
results.push(...attached);
});
return results;
}
// 반복문 => 가능한 모든 케이스 탐색
for(i=1;i<=text.length;i++){
allPossibleCases.push((getPermutations(text.split(""),i)))
}
// 모든 케이스들중 소수 조건 만족 케이스 탐색
for(i=0;i<allPossibleCases.length;i++){
for(j=0;j<allPossibleCases[i].length;j++){
const testNumber=parseInt(allPossibleCases[i][j].join(""))
if(isPrime(testNumber)){
allPossilblePrimeCases.push(testNumber)
}
}
}
// 중복 제거
return(new Set(allPossilblePrimeCases).size)
}
728x90
'알고리즘' 카테고리의 다른 글
프로그래머스 > Summer/Winder Coding(~2018) > 방문 길이 (0) | 2023.04.03 |
---|---|
프로그래머스 > 카카오 개발자 겨울 인턴십 > 튜플 (0) | 2023.04.01 |
자바스크립트 문자열 문제풀이 (0) | 2023.03.24 |
자바스크립트 배열 문제풀이 (0) | 2023.03.23 |
자바스크립트 반복문 문제풀이 (0) | 2023.03.23 |