프로그래머스 LEVEL 1(삼총사)
-
사용 언어 : javascript
-
해결 날짜 : 2022-10-18
- 해결 방법 :
- number 배열 속 3개의 원소를 가지는 조합 구하기
- 조합 돌며 합이 0일 때 answer 증가
- 회고 :
- x
-
코드
const getCombinations = (arr, num) => { const results = []; if (num === 1) return arr.map(v => [v]); arr.forEach((fixed, index, origin) => { const rest = origin.slice(index + 1); const combinations = getCombinations(rest, num - 1); const attached = combinations.map(v => [fixed, ...v]); results.push(...attached); }); return results; } function solution(number) { let answer = 0; const combinations = getCombinations(number, 3); for (const combination of combinations) { if (combination.reduce((acc, cur) => acc + cur, 0) === 0) answer++; } return answer; }
- 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges