Jieunny์˜ ๋ธ”๋กœ๊ทธ

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์†Œ์ˆ˜ ์ฐพ๊ธฐ ๋ณธ๋ฌธ

Study/Coding Test

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์†Œ์ˆ˜ ์ฐพ๊ธฐ

Jieunny 2023. 9. 20. 18:27

๐Ÿ“Œ ๋ฌธ์ œ

ํ•œ์ž๋ฆฌ ์ˆซ์ž๊ฐ€ ์ ํžŒ ์ข…์ด ์กฐ๊ฐ์ด ํฉ์–ด์ ธ์žˆ์Šต๋‹ˆ๋‹ค. ํฉ์–ด์ง„ ์ข…์ด ์กฐ๊ฐ์„ ๋ถ™์—ฌ ์†Œ์ˆ˜๋ฅผ ๋ช‡ ๊ฐœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋‚ด๋ ค ํ•ฉ๋‹ˆ๋‹ค.

๊ฐ ์ข…์ด ์กฐ๊ฐ์— ์ ํžŒ ์ˆซ์ž๊ฐ€ ์ ํžŒ ๋ฌธ์ž์—ด numbers๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ข…์ด ์กฐ๊ฐ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์†Œ์ˆ˜๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

๐Ÿ’ก ์•„์ด๋””์–ด 

์ˆœ์—ด + ์†Œ์ˆ˜ ์ฐพ๊ธฐ + Set ํ™˜์žฅ ์กฐํ•ฉ..

 

โœ๏ธ ํ’€์ด

function solution(numbers) {
    const arr = numbers.split('');
    const primeSet = new Set();
    // ๊ฐ™์€ ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ๋ฒˆ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ์œผ๋‹ˆ๊นŒ Set์œผ๋กœ ์ค‘๋ณต ์ œ๊ฑฐํ•ด์ฃผ๊ธฐ
    
    for(let i=1; i<=numbers.length; i++) {
        const permutaion = permutations(arr, i);
        for(let i=0; i<permutaion.length; i++) {
           if(isPrime(Number(permutaion[i].join("")))){
               primeSet.add(Number(permutaion[i].join("")));
              }                 
        }
    }
    return primeSet.size;
}


// ์กฐํ•ฉํ•ด์„œ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์ˆ˜ ๊ตฌํ•˜๊ธฐ(์ˆœ์—ด)
function permutations(arr, num) {
    const result = [];
    if(num === 1) return arr.map((el) => [el]);
    
    arr.forEach((fixed, index, origin) => {
        const rest = [...origin.slice(0, index), ...origin.slice(index+1)];
        const permutation = permutations(rest, num - 1);
        const attached = permutation.map((el) => [fixed, ...el]);
        result.push(...attached);
    })
    return result;
} 

// ์†Œ์ˆ˜ ํŒ๋ณ„
function isPrime(num) {
    if(num === 1 || num === 0) return false;
    for(let i=2; i<=Math.sqrt(num); i++) {
        if(num % i === 0) return false;
    }
    return true;
}