본문 바로가기
알고리즘/프로그래머스

[프로그래머스][자바스크립트][Level1] 두 개 뽑아서 더하기

by Benjamin_Choi 2022. 1. 6.


/**
 * 두개뽑아서더하기.js
 * https://programmers.co.kr/learn/courses/30/lessons/68644?language=javascript
 */

// combination
function solution(numbers) {
    const numSet = new Set(getCombinationsSum(numbers, 2));

    return Array.from(numSet).sort((a, b) => a - b);
}

function getCombinationsSum(array, selectedNum) {
    const results = [];
    if (selectedNum === 1) {
        return [...array];
    }
    array.forEach((fix, idx, orgArr) => {
        const restArr = orgArr.slice(idx + 1);
        const combination = getCombinationsSum(restArr, selectedNum - 1);
        const attachSum = combination.map((num) => fix + num);
        results.push(...attachSum);
    });

    return results;
} 

module.exports = solution;

2개씩 뽑아서 더하는 것으로 combination 응용해서 2개씩 뽑아서 다 더하는 함수를 만들고, 겹치는 값을 제거 하기위해 Set을 사용했다.


/**
 * 두개뽑아서더하기.test.js
 */

const solution = require("./두개뽑아서더하기");

test('[2,1,3,4,1]', () => {
    expect(solution([2,1,3,4,1])).toEqual([2,3,4,5,6,7]);
});

test('[5,0,2,7]', () => {
    expect(solution([5,0,2,7])).toEqual([2,5,7,9,12]);
});

 

댓글