Notice
Recent Posts
Recent Comments
Link
ยซ   2024/12   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.2] ์†Œ์ˆ˜ ์ฐพ๊ธฐ (js) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.2] ์†Œ์ˆ˜ ์ฐพ๊ธฐ (js)

Lennon 2021. 11. 12. 23:35
728x90
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/42839?language=javascript 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์†Œ์ˆ˜ ์ฐพ๊ธฐ

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

programmers.co.kr

 

function solution(numbers) {

    const number = [...numbers];
    const answer = [];    
    
    for(let i = 1; i <= number.length; i++){
        permutation(number,i).forEach((v) => {
            isPrime(+v) ? answer.push(+v) : answer
        });
    }
    return [...new Set(answer)].length
}

function isPrime(num){
    let start = 2;
    while (start <= Math.sqrt(num)) {
        if (num % start++ < 1){
            return false;
        }
    }
    return num > 1;
}

function permutation(arr, selectNum){
        const result = [];
        if(selectNum === 1) return arr.filter((v)=> [v]);

        arr.forEach((v,idx,arr)=>{
            const fixer = v;
            const restArr = arr.filter((val, index)=> index !== idx);
            const permuArr = permutation(restArr, selectNum-1);
            const combineFixer = permuArr.map((v)=> fixer + v);
            result.push(...combineFixer);
        })
        return result;
    }

 

permutation ํ•จ์ˆ˜ => arr => ๋ฐฐ์—ด selectNum => ๊ฐœ์ˆ˜ 

 

                            selectNum๋งŒํผ ์กฐํ•ฉํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜ / ์ค‘๋ณต๊นŒ์ง€ ์ „๋ถ€ ๋“ค์–ด๊ฐ (011, 11, 0011) ๋‚˜์ค‘์— ์ฒ˜๋ฆฌ

 

 

isPrime ํ•จ์ˆ˜ => ์†Œ์ˆ˜ ์ฒดํฌ ํ•จ์ˆ˜์ด๋‹ค. ์ œ๊ณฑ๊ทผ์„ ํ†ตํ•ด ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

 

 

solution์—์„œ ์กฐํ•ฉํ•œ ๊ฒฐ๊ณผ๋ฅผ answer์— ์ „๋ถ€ ๋‹ด๊ณ  ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ธฐ ์œ„ํ•ด Set์„ ์‚ฌ์šฉํ•œ ํ›„ answer์˜ ๊ธธ์ด๋ฅผ ๋ฆฌํ„ดํ•˜๋ฉด ๋!

 

728x90
๋ฐ˜์‘ํ˜•
Comments