gpt4 book ai didi

javascript - 基于多条件/因素的排名算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:51 24 4
gpt4 key购买 nike

我正在写一个小游戏,但最后卡住了。这是一个简单的测验,它根据正确回答的问题数量和完成一组问题所需的时间对用户进行排名。

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

最佳答案

您可以在 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

关于javascript - 基于多条件/因素的排名算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38196161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com