문제
풀이 1
function solution(numbers) {
var answer = 0;
function getPermutations(arr, selectNumber ) {
let result = []
if (selectNumber===1) return arr.map(v=>[v])
arr.forEach( (fixed,index,origin) => {
let remain = [ ...arr.slice(0,index) , ...arr.slice(index+1,)]
let permutations = getPermutations(remain, selectNumber-1)
result.push(...permutations)
let attach = permutations.map(permutation => [fixed, ...permutation])
result.push(...attach)
})
return result
}
function primeNumber(n) {
if (n===1 || n===0) return false
for (let i=2; i<=Math.sqrt(n); i++ ){
if (n % i===0) return false
}
return true
}
let result = [...new Set(getPermutations(numbers.split('') , numbers.length).map(v=>parseInt(v.join(''))))].sort((a,b) => a-b)
result.map(v => primeNumber(v) ? answer++ : 0)
return answer;
}
풀이 2
function solution(numbers) {
var answer = 0;
var n = numbers.split('');
var nums = new Set()
combi(n,'');
function combi(a, s) {
if (s.length > 0) {
if (nums.has(Number(s))=== false) {
nums.add(Number(s));
console.log(Number(s))
if (chkPrime(Number(s))) {
answer++;
}
}
}
if (a.length > 0) {
for (var i = 0; i< a.length; i++) {
var t = a.slice(0)
t.splice(i,1);
combi(t,s + a[i]);
}
}
}
function chkPrime(num) {
if (num < 2) return false;
if (num === 2) return true;
for (var i = 2; i <= Math.sqrt(num); i++) {
if (num%i===0) return false;
}
return true;
}
return answer;
}
풀이 3
function solution(numbers) {
var answer = 0;
var set = new Set();
makeNumbers(set , '' , numbers.split(''));
return set.size;
}
function issosu(num) {
if( num < 2) return false;
for (var i =2; i <= num / 2 ; i++) {
if( num % i === 0) return false;
}
return true;
}
function makeNumbers(set , cur, nums) {
if( nums.length === 0 ) return;
var clone = nums.slice().reverse();
nums.forEach(function(i) {
var su = clone.pop();
var num = Number(cur+su);
if ( issosu(num)) {
set.add(num);
}
makeNumbers(set, cur+su , clone);
clone.unshift(su);
})
}