Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

나 개발자 할래요

[JS] 두 개 뽑아서 더하기 본문

개발자 되는 법.../코딩테스트...

[JS] 두 개 뽑아서 더하기

개발_자 2024. 7. 15. 21:31

function solution(numbers) {
    var answer = [];
    for(let i = 0; i < numbers.length; i++) {
        for(let j = i + 1; j < numbers.length; j++) {
            let sum = numbers[i] + numbers[j];
            if(answer.indexOf(sum) === -1) {
                answer.push(sum);
            }
        }
    } answer.sort((a, b) => a - b);
    return answer;
}

 

`.indexOf()`

배열에서 특정 요소의 첫 번째 인덱스를 반환하는 메서드

요소가 배열에 없으면 `-1`을 반환

 

 

`answer.indexOf(sum) === -1` 조건이 참이면

`sum`이 `answer`배열에 없다는 뜻

 

 

 

 


 

 

 


다른 사람 풀이

function solution(numbers) {
    const temp = []

    for (let i = 0; i < numbers.length; i++) {
        for (let j = i + 1; j < numbers.length; j++) {
            temp.push(numbers[i] + numbers[j])
        }
    }

    const answer = [...new Set(temp)]

    return answer.sort((a, b) => a - b)
}

 

`...new Set`

Set 객체를 배열로 변환하는 방법

 

 

Set 객체

고유한 값들의 집합 저장

배열과 달리 Set은 중복된 값 허용하지 않음

 

스프레드 연산자 (...)

배열이나 객체의 모든 요소를 개별요소로 분리할 때 사용

 

 

`temp`배열

모든 가능한 두 숫자의 합 저장 (중복된 합도 포함될 수 있음)

`new Set(temp)`

`temp` 배열에서 중복된 값을 제거한 Set 객체 만듦

`...new Set(temp)`

Set 객체의 요소를 개별적으로 분리하여 새로운 배열 `answer` 만듦