基于多个条件/因素的排序算法 [英] ranking algorithm base on multiple condition/factor

查看:471
本文介绍了基于多个条件/因素的排序算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写迷你游戏,但最终还是陷入困境。这是一个简单的测验,它根据正确回答的问题数和完成问题集所需的时间对用户进行排名。

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.

我可以轻松地根据回答的人对用户进行排名问题最多,但是如何根据2个条件来计算谁是表现最好的人呢?

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?

推荐答案

您可以在一个条件中处理多个条件

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

示例:

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
  });
}

输出:

#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

这篇关于基于多个条件/因素的排序算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆