[프로그래머스]해시--완주하지 못한 선수(with js)

장현광·2021년 4월 20일
0

알고리즘

목록 보기
2/8
post-thumbnail

첫 번째 시도

function solution(participant, completion) {
    let answer = '';
    
    answer = participant.filter(el => !completion.includes(el))
    
    return answer;
}

의도

filterparticipant의 원소 중, completion에는 없는 원소를 찾아내려 하였다.

하지만 내가 생각하지 못한 게 두 가지가 있다.
1. arr.filter()를 하면 배열을 return 한다.
2. participant에 이름이 같은 원소 가 2개가 있을 수 있다.

해결

첫 번째 문제점은 어떻게든 해결가능 하지만, 두 번째는 어떻게 해결할까 고민해 보았다.
우선 떠오른 방법은, 편법같아 보이지만 동명이인이 있을 경우 그 사람을 answerreturn 하는 것. 무조건 completion이 한 명 적기 때문에 가능 한 방법이다.

두 번째 시도

function solution(participant, completion) {
    let answer = '';
    const isSole = participant.filter(el => !completion.includes(el))
    
    if(isSole.length === 1) {
        answer = isSole[0]
    } else {
        for(let i = 0; i < participant.length; i++) {
            for(let j = i + 1; j < participant.length; j++) {
                if(participant[i] === participant[j]) {
                    answer = participant[i]
                }
            }
        }
    }
    return answer;
}

if문에서 동명이인이 있는지 체크하고 없으면

보고 있자니 코드가 너무 더러운 것 같다....;;
결과도 좋지는 않다..

문제점

동명이인이 한 쌍밖에 없는 경우에만 유효하다.

participant = ["mislav", "stanko", "mislav", "ana", "mislav", "ana"]
completion = ["stanko", "ana", "mislav", "mislav", "ana"]

일 경우 answer = mislav이지만 ana가 나온다.
그래서 새롭게 접근해보았다. participantcompletionsort() 하고 앞에서부터 비교하는 것이다.

세 번째 시도

function solution(participant, completion) {
    let answer = '';
    participant.sort();
    completion.sort();
    
    for(let i = 0; i < participant.length; i++) {
        if(participant[i] !== completion[i]) {
            answer = participant[i]
            break
        }
    }
    
    return answer
}

결과는?

짠! 🎺🎺
문득 떠오른 방법으로 해보았는데 한번에 효율성 테스트까지 통과했다.
사실 해시가 뭔지도 모르고 시작한 문제였는데, 이 기회에 해시를 공부해봐야겠다.

우연찮게 알게 된 내용

if('') {
    console.log('true')
} else {
    console.log('false')
}

if([]) {
    console.log('true')
} else {
    console.log('false')
}

// 'false'
// 'true'

''false로 취급되지만 []true로 취급된다.

profile
프론트!

0개의 댓글