프로그래머스-두 개 뽑아서 더하기

이서현·2021년 6월 9일
0

Algorithm

목록 보기
35/76

06.09에 푼 문제입니다🌷
두 개 뽑아서 더하기

조합으로 두 개의 수를 뽑아서 계산한다.
Set을 이용해서 중복되는 수를 제거한다🔥

function solution(numbers) {
    var answer = [];
    var combination=getCombination(numbers,2)
    
    combination.map(com=>answer.push(com[0]+com[1]))
    answer.sort((a,b)=>a-b)
    return [...new Set(answer)];
}

function getCombination(numbers,num){
    const result=[]
    if(num===1) return numbers.map(num=>[num])
    
    numbers.forEach((fixed,index,origin)=>{
        const rest=origin.slice(index+1)
        const combination=getCombination(rest,num-1)
        const attach=combination.map(com=>[fixed,...com])
        
        result.push(...attach)
    })
    
    return result
}
profile
안녕하세요. 이서현입니다( ღ'ᴗ'ღ )

0개의 댓글