문제
https://school.programmers.co.kr/learn/courses/30/lessons/42839
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
function solution(numbers){
const answer = [];
const nums = numbers.split('');
const length = nums.length;
const isVisited = Array.from({length:length}, ()=>false);
const arr = Array.from({length:length}, ()=>0);
function dfs(cnt){
if(cnt!==0){
let s = '';
for(let i=0; i<cnt; i++){
s+=arr[i];
}
if(isPrime(Number(s))) answer.push(Number(s));
}else if(cnt===length) return;
for (let i=0; i<length; i++){
if(!isVisited[i]){
isVisited[i]=true;
arr[cnt]=nums[i]
dfs(cnt+1)
isVisited[i]=false;
}
}
}
dfs(0);
return [...new Set(answer)].length
}
function isPrime(n){
if(n<2) return false;
for(let i=2; i<=Math.sqrt(n); i++){
if(n%i===0) return false;
}
return true;
}
정리
소수 판별 함수
function isPrime(n){
if(n<2) return false;
for(let i=2; i<=Math.sqrt(n); i++){
if(n%i===0) return false;
}
return true;
}
string 배열화
const nums = numbers.split(''); // '123' -> ['1', '2', '3']
배열 초기화 - Array.from({length: ...}, ()=>{})
const isVisited = Array.from({length:length}, ()=>false);
const arr = Array.from({length:length}, ()=>0);
참조
'Programmers' 카테고리의 다른 글
| [프로그래머스] 같은 숫자는 싫어 (JS) (0) | 2023.11.12 |
|---|---|
| [프로그래머스] 가장 큰 수 (JS) - sort (0) | 2023.11.11 |
| [프로그래머스] K번째수 (JS) - sort (0) | 2023.11.10 |
| [프로그래머스] 모의고사 (JS) - 완전탐색 (0) | 2023.11.09 |
| [프로그래머스] 신고 결과 받기 (C++, JS) (1) | 2023.11.08 |