Home > other >  Runner Up Score - Solution in Javascript
Runner Up Score - Solution in Javascript

Time:06-23

I'm currently still learning the basic JS and wondering how to answer this array type of question.

Question

//Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given N scores. Store them in a list and find the score of the runner-up.

//Input Format

//The first line contains N. The second line contains an array A[] of N integers each separated by a space.

//Output Format

//Print the runner-up score.

//Sample Input: [5,2,3,6,6,5]
//Sample Output: 5

This is my code

function uniqueScore (value, index, self) {
   return self.indexOf(value) === index
}
var score = [5,2,3,6,6,5]
var filter = score.filter(uniqueScore)
var descSort = filter.sort().reverse()

function runnerUpScore(x) {
    var runnerUp = descSort
    return runnerUp
}
console.log(runnerUpScore(x))

The condition is i'm stuck when already sorting the array and removing duplicate. Hence, I need some guidance how to call the sorted array and only showing the index 1 from array list to show the runner up score.

CodePudding user response:

The problem with your approach is you are sorting the array and then reversing it which costs lots of computation. Here is a simple solution in O(n). It iterates the array only once and finds the second-largest score, which is the runner-up score.

var scores = [1,2,3,4,5];

const runnerUpScore = (scores) => {
  scores = [... new Set(scores)] // get unique elements
  var largest = -1;
  var secondLargest = -1;
  
  scores.forEach((score) => {
    if(score >= largest) {
      secondLargest = largest;
      largest = score;
    } else if (score > secondLargest) {
      secondLargest = score;
    }
  });
  
  return secondLargest;
}

console.log(runnerUpScore(scores));

CodePudding user response:

  1. .sort() reverse:
    let scores = [5, 2, 3, 6, 6, 5];
    let reverseOrder = scores.sort((a, b) => b - a);
    // [6, 6, 5, 5, 3, 2]
    
  2. Filter out duplicates by converting array into a Set() then back to an array:
    let set = new Set(reverseOrder)
    // {6:6, 5:5, 3:3, 2:2} this is a representation there's much more to a Set.
    let unique = [...set]
    // [6, 5, 3, 2]
    
  3. Get the score in the second index position:
    unique[1]
    // 5
    

const scores = [5, 2, 3, 6, 6, 5];

const reverseOrderUnique = [...new Set(scores.sort((a, b) => b - a))];

console.log(reverseOrderUnique);
console.log('Runner Up: ' reverseOrderUnique[1]);

  • Related