프로그래머스- 소수 찾기(완전탐색)

Minji·2022년 5월 17일
0

문제

https://programmers.co.kr/learn/courses/30/lessons/42839

풀이

  1. 종이조각으로 만들 수 있는 숫자들을 먼저 구함
    -> 순서가 중요하니까 순열
  2. 숫자들이 소수인지 아닌지 확인

✅ 순열과 조합

//순열과 조합 알고리즘(소수 찾기에서 헷갈렸던 것)
const getPermutation=(arr,num)=>{
    const result=[];
    //1개씩 택할 때는 모든 배열의 원소 return 하면 됨
    if(num===1) return arr.map((value)=>[value])

    arr.forEach((current,idx,origin)=>{
        const fixed=current; //고정된 값 한개
        console.log(fixed)
        const restArr=[...origin.slice(0,idx),...origin.slice(idx+1)] //fixed 빼고 나머지
        const permutations=getPermutation(restArr,num-1);// 나머지로 순열 구하기
        const attached=permutations.map((permutation)=>[fixed,...permutation])//순열+fixed값
        result.push(...attached)
        console.log(result)
    });
    return result;
}
// 조합 구하기
const getCombination=(arr,num)=>{
    const result=[];
    if(num===1) return arr.map((value)=>[value])
    arr.forEach((current,idx,origin)=>{
        const fixed=current;
        const restArr=origin.slice(idx+1)
        const combinations=getCombination(restArr,num-1)
        const attached=combinations.map((combination)=>[fixed,...combination]);
        result.push(...attached)
    })
    return result;
}


console.log(getPermutation([1,2,3,4],3));
console.log(getCombination([1,2,3,4],3))

코드 이해하기 위해서 손으로 직접 해보니까 이해가 잘 감

✅ slice()

arr.slice(begin,end) 배열의 begin부터 end(end는 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환함
원본 배열은 변화없음
arr.slice(2) 이면 2부터 끝까지

✅ splice()

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
splice(1,1,'arr') index=1부터 1개 삭제하고 'arr'추가
splice(1,1) index=1부터 1개 삭제

function solution(numbers){
  	//중복 제거를 위해 Set() 사용_텍스트_
    var answer=new Set();
    var tmp=[]
    const getPermutation=(arr,str)=>{
        for(let i=0;i<arr.length;i++){
            let tmp=[...arr];
            tmp.splice(i,1)
            getPermutation(tmp,str+arr[i])
        }
        if(str>0) answer.add(Number(str))
    }
    getPermutation([...numbers],'')
    tmp=[...answer]
    tmp=tmp.filter(v=>{
        n=0;
        for(let i=1;i<=v;i++){
            if(parseInt(v)%i===0) n+=1
        }
        if(n===2) return parseInt(v)
    })
    return tmp.length;
}

참고

https://pul8219.github.io/algorithm/algorithm-permutation-and-combination/
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

profile
매일매일 성장하기 : )

0개의 댓글