Eunice Chia Eunice Chia - 5 months ago 22
Javascript Question

ranking algorithm base on multiple condition/factor

I'm writing a mini game but stuck in the end. It's a simple quiz where it rank user by the number of question correctly answered and the time taken to finish the set of questions.

I easily can rank user base on who answered the most question, but how do I calculate who's the best performer base on 2 conditions?

Answer

You can process several conditions in a single pass in the comparison function of Array.prototype.sort().

Example:

var score = [];

storeScore('user1', 7, 65); // 7 correct answers in 65 sec.
storeScore('user2', 8, 70); // 8 correct answers in 70 sec.
storeScore('user3', 6, 50); // 6 correct answers in 50 sec.
storeScore('user4', 7, 50); // 7 correct answers in 50 sec.

score = score.sort(function(a, b) {
  return b.correct > a.correct || (b.correct == a.correct && b.time < a.time);
});

for(var id in score) {
  console.log(
    '#' + ((id | 0) + 1),
    score[id].userId,
    score[id].correct + ' correct answers in ' +
    score[id].time + ' seconds'
  );
}

function storeScore(userId, correct, time) {
  score.push({
    userId : userId,
    correct: correct,
    time   : time
  });
}

Output:

#1 user2 8 correct answers in 70 seconds
#2 user4 7 correct answers in 50 seconds
#3 user1 7 correct answers in 65 seconds
#4 user3 6 correct answers in 50 seconds