728x90
사실 두개정도면 for문 2개를 활용하는게 더 좋았을 거 같긴 한데, 이전에 순열 뽑아내는 알고리즘을 한번 복습하고 싶어서 순열을 활용해서 풀어보았다.
순열 알고리즘을 활용해서 모든 경우의 수를 가져온 다음, set자료형을 활용해서 중복을 없애주었다.
const getCombinations = (n,ary) => {
const ret = []
if (n===1) return ary.map(el => [el])
ary.forEach((fixed,idx,origin) => {
const rest = ary.slice(idx+1);
const combinations = getCombinations(n-1,rest)
const attach = combinations.map(el => [fixed , ...el ])
ret.push(...attach)
})
return ret
}
function solution(numbers) {
var answer = [ ...new Set(getCombinations(2,numbers).map(el => el[0]+el[1]))].sort((a,b) => a-b);
return answer;
}
728x90
'FrontEnd > 프로그래머스' 카테고리의 다른 글
[JS] 크레인 인형뽑기 (1) | 2023.04.23 |
---|---|
[JS] 키패드누르기 (0) | 2023.04.21 |
[JS] 신규 아이디 추천 (0) | 2023.04.20 |
[JS] 내적 (0) | 2023.04.20 |
[JS] 로또의 최고순위와 최저순위 (0) | 2023.04.18 |