/**
* 두개뽑아서더하기.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]);
});
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스][자바스크립트][Level1] 문자열 내림차순으로 배치하기 (0) | 2022.01.06 |
---|---|
[프로그래머스][자바스크립트][Level1] 2016년 (0) | 2022.01.06 |
[프로그래머스][자바스크립트][Level1][카카오] 실패율 (0) | 2022.01.05 |
[프로그래머스][자바스크립트][Level2] H-Index (0) | 2022.01.04 |
[프로그래머스][자바스크립트][Level2] 가장 큰 수 (0) | 2022.01.04 |
댓글