FrontEnd/프로그래머스

[JS] 삼총사

728x90

배열의 순열을 구해서, 각 순열마다 합을 계산해본 후, 0올때마다 reduce를 활용해서 개수를 세 주었다.

 

const getCombination = (arr,num) => {
    const ret = []
    if (num === 1) return arr.map(el => [el])
    arr.forEach((fixed,idx,origin)=> {
        const rest = origin.slice(idx+1);
        const combinations = getCombination(rest,num-1)
        const attached = combinations.map(el => [fixed, ...el]);
        ret.push(...attached)
    })
    return ret
}

function solution(number) {
    return getCombination(number,3).reduce((a,c) => {
        return c.reduce((a,c) => a+c , 0) ? a : a+1
    },0);
}
728x90

'FrontEnd > 프로그래머스' 카테고리의 다른 글

[JS] 성격 유형 검사하기  (0) 2023.04.16
[JS] 숫자 짝꿍 (쉬운풀이 ?)  (0) 2023.04.13
[JS] 콜라 문제  (0) 2023.04.11
[JS] 옹알이 (2)  (0) 2023.04.10
[JS] 햄버거 만들기  (0) 2023.04.10