[프로그래머스]소수 찾기(javascript/자바스크립트)

스카치·2023년 3월 29일
0

문제

풀이 1

function solution(numbers) {
    var answer = 0;
    
    // numbers 부분순열구하기
    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
    }
    
    // 소수 인지 판별  -> 맞으면 primeNumber.push(parseInt(소수)) -> 리턴 new Set(primeNumber) 
    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);
                //console.log(t)
                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);
    }) 
}

0개의 댓글