function solution(participant, completion) {
let answer = '';
answer = participant.filter(el => !completion.includes(el))
return answer;
}
filter
로 participant
의 원소 중, completion
에는 없는 원소를 찾아내려 하였다.
하지만 내가 생각하지 못한 게 두 가지가 있다.
1. arr.filter()
를 하면 배열을 return
한다.
2. participant
에 이름이 같은 원소 가 2개가 있을 수 있다.
첫 번째 문제점은 어떻게든 해결가능 하지만, 두 번째는 어떻게 해결할까 고민해 보았다.
우선 떠오른 방법은, 편법같아 보이지만 동명이인이 있을 경우 그 사람을 answer
로 return
하는 것. 무조건 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
가 나온다.
그래서 새롭게 접근해보았다. participant
와 completion
을 sort()
하고 앞에서부터 비교하는 것이다.
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
로 취급된다.