[프로그래머스 Level 1] 두개 뽑아서 더하기
정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.
// # 1st
function solution(numbers) {
const answer = [];
for (const fixedIndex in numbers) {
const value = numbers[fixedIndex];
for (const numberIndex in numbers) {
if (fixedIndex !== numberIndex) answer.push(value + numbers[numberIndex]);
}
}
return answer
.sort((a, b) => a - b)
.reduce((acc, curr) => (acc.includes(curr) ? acc : [...acc, curr]), []);
}
const numbers1 = [2, 1, 3, 4, 1];
console.log(solution(numbers1)); // [ 2, 3, 4, 5, 6, 7 ]
1차로 제출했을 당시 코드이다.
객체 순회를 위해for of
를 사용 하려고 했는데, 요소별 인덱스 번호가 필요했다.
그래서 임시방편으로 for in
을 이용해서 인덱스 번호로 요소에 접근하여 문제를 풀었다.
그런데 여기서 문제는 배열에는 for in
을 사용하면 안된다. MDN 문서를 보면 "for..in
문은 임의의 순서로 객체의 속성들에 대해 반복합니다.."라고 설명하고 있다. 객체는 고유한 key
값으로 각 프로퍼티에 접근을 해서 순서에 관계가 없다. 그러나 배열은 순서가 매우 중요하다.
같은 동작을 할수있는 forEach
를 이용해 보자.
// # 2nd
function solution(numbers) {
const answer = [];
numbers.forEach((value, fixedIndex) => {
numbers.forEach((currentValue, numberIndex) => {
if (fixedIndex !== numberIndex) answer.push(value + currentValue);
});
});
return answer
.sort((a, b) => a - b)
.reduce((acc, curr) => (acc.includes(curr) ? acc : [...acc, curr]), []);
}
const numbers1 = [2, 1, 3, 4, 1];
console.log(solution(numbers1)); // [ 2, 3, 4, 5, 6, 7 ]
이렇게 2차로 코드를 수정해보았다.
- 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return
(중복값을 허용하지 않는 배열)
- 서로 다른 인덱스
if(fixedIndex !== numberIndex)
- 오름차순
sort((a, b) => a - b)
- 중복제거
.reduce((acc, curr) => (acc.includes(curr) ? acc : [...acc, curr]), []);