Algorithm training - 완주하지 못한 선수

1 minute read

  1. Algorithm

    • programmers.co.kr coding test practice level 1
    • Logic 완주
    • Given input and expected output 입출력
  2. The first solution I came up with, but I didn’t consider cases of people with same name.

    • Add filter to compare the two lists
function solution(participant, completion) {
    var answer = participant.filter(x => !completion.includes(x)).toString();
    return answer;
}
  • It passed input 1 and 2 but issue was found on case number 3 that contains people with same name.
  1. Second attempt
    • Would I be able to compare the two list easier if I sort the lists?
    • Or should I compare them while I delete matched items from both lists?
    • I assumed that sorting might be complicated and decided to go with deleting items.
function solution(participant, completion) {
  var number = completion.length;
  for (var i = 0; i < number; i++) {
    var target = completion[i].toString();
    var a = participant.indexOf(target);
    participant = participant.splice(a, 1);
    completion = completion.splice(i, 1);
  }
  var answer = participant.toString();
  return answer;
}
  1. Fail
    • The code became messy. Did not work well and even if it did it would have taken long time to process.
function solution(participant, completion) {
    participant.sort();
    completion.sort();
    for(var i=0;i<participant.length;i++){
        if(participant[i] !== completion[i]){
            return participant[i];
        }
    }
}
  • Found other people’s solution.
function solution(participant, completion) {
    participant.sort();
    completion.sort();
    for(var i=0;i<participant.length;i++){
        if(participant[i] !== completion[i]){
            return participant[i];
        }
    }
}
  • The reason of this failure was that I gave up on an idea that could have worked.
  • I did not know about sort() Method. I ended up making a mess from the algorithm practice number one but it’s OK. It’s just a beginning. I think I am getting anxious because of my upcoming bootcamp and not having finished Vanilla JS study. Let’s keep on working and not worry about things too much.