我经常玩一个游戏,每个玩家都有一个评分。例如1678或1820。当您赢得游戏时,您将获得积分;当您输球时,您将失去积分。
现在,当8位玩家加入一个大厅时,我们希望拥有相等的团队(4v4),或者尽可能接近,以进行分级。总会有2支队伍和3到8名球员(也可以是2v1等不平衡的队伍)。
我可以使用什么算法在JavaScript中创建两个相等的团队?
例如:
ratings = [1466, 1678, 1988, 1200, 1362, 1555, 1844, 1600];
team 1: [xxxx,xxxx,xxxx,xxxx] ??
team 2: [xxxx,xxxx,xxxx,xxxx] ??
答案 0 :(得分:1)
我知道您使用javascript询问过,但也许对您有所帮助。 我所做的就是获得数组的平均值(所有值的总和和/到团队数,在我的情况下是2个团队)=> 排序数组=> 将值推入team1数组,直到team1数组的总和>然后取平均值=> 其余部分推入team2阵列
ratings = [1306, 1578, 1458, 1450,1602, 1355, 1454, 1300]
from functools import reduce
class match_making(object):
team1 = []
team2 = []
def __init__(self,ratings):
self.ratings = ratings
def get_value(self):
self.average_value = reduce(lambda x,y: x + y / 2 ,self.ratings)
def split_players (self):
x = 0
for player in sorted(self.ratings):
x = x + player
if x < self.average_value:
self.team1.append(player)
print(x)
elif x > self.average_value:
self.team2.append(player)
def dowork(self):
self.get_value()
self.split_players()
some = reduce(lambda x , y :x +y , self.team1) #just too see average rating of the team1
some2 = reduce(lambda x , y :x +y , self.team2)# same as above for team2
return some,some2,self.team1,self.team2
divide_players = match_making(ratings)
print(divide_players.dowork())
答案 1 :(得分:0)
对其进行了编辑以使其更加简洁,并将比较移到外面以使其更加清晰。但这是按等级排序后球员的基本分布。
let ratings = [1466, 1678, 1988, 1200, 1362, 1555, 1844, 1600];
let team1 = [];
let team2 = [];
const sortNumber = (n1, n2) => {
if(n1 > n2) return -1;
if(n1 < n2) return 1;
return 0;
};
// Simple distibution
function distributePlayers(arrPlayers) {
let sortedPlayers = arrPlayers.sort(sortNumber);
console.log(sortedPlayers);
let teams = [[],[]];
sortedPlayers.forEach((player, index) => {
teams[index%2].push(player);
});
return teams;
}
distributePlayers(ratings).forEach(team => {
console.log(team);
});
这是一个基本的排序和分发。
let ratings = [1466, 1678, 1988, 1200, 1362, 1555, 1844, 1600];
let team1 = [];
let team2 = [];
// Simple distibution
function distributePlayers(arrPlayers) {
let sortedPlayers = arrPlayers.sort((p1, p2) => {
if(parseInt(p1) > parseInt(p2)) {
return -1;
} else if (parseInt(p1) < parseInt(p2)) {
return 1;
}
return 0;
});
console.log(sortedPlayers);
let teams = [[],[]];
sortedPlayers.forEach((player, index) => {
let teamIndex = index%2;
teams[(teamIndex)].push(player);
});
return teams;
}
distributePlayers(ratings).forEach(team => {
console.log(team);
})
答案 2 :(得分:0)
您可以先对其进行排序,然后根据每个元素的总和添加到第一或第二个数组中。
function distribute(arr) {
arr.sort().reverse()
let a = [], b = [], sumA = 0, sumB = 0, i = 0
while (i < arr.length) {
if (!sumA && !sumB || sumA == sumB) {
a.push(arr[i])
sumA += arr[i]
} else if (sumA < sumB) {
a.push(arr[i])
sumA += arr[i];
} else if (sumB < sumA) {
b.push(arr[i])
sumB += arr[i];
}
i++
}
console.log(`Total: ${sumA} ${sumB}`)
return [a, b]
}
console.log(distribute([1466, 1678, 1988, 1200, 1362, 1555, 1844, 1600]))
console.log(distribute([1466, 6000, 1988, 1200, 1362, 1555, 1844, 1600]))