FrontEnd/프로그래머스

[JS] 두개 뽑아서 더하기

정_민_규 2023. 4. 20. 18:13
728x90

사실 두개정도면 for문 2개를 활용하는게 더 좋았을 거 같긴 한데, 이전에 순열 뽑아내는 알고리즘을 한번 복습하고 싶어서 순열을 활용해서 풀어보았다.

 

순열 알고리즘을 활용해서 모든 경우의 수를 가져온 다음, set자료형을 활용해서 중복을 없애주었다.

 

const getCombinations = (n,ary) => {
    const ret = []
    if (n===1) return ary.map(el => [el])
    
    ary.forEach((fixed,idx,origin) => {
        const rest = ary.slice(idx+1);
        const combinations = getCombinations(n-1,rest)
        
        const attach = combinations.map(el => [fixed , ...el ])
        ret.push(...attach)
    })
    return ret
}

function solution(numbers) {
    var answer = [ ...new Set(getCombinations(2,numbers).map(el => el[0]+el[1]))].sort((a,b) => a-b);
    return answer;
}
728x90