为了让它更清晰我有一个玩家ID数组,我想平均和随机地分成X个组,但是当数字是奇数时,组1需要是具有少量部分的子阵列:like这个例子:
我的数字是偶数的情况更容易,但我不知道如何实现这种情况。我需要一些帮助才能知道如何做。
答案 0 :(得分:2)
按顺序挑选玩家并将其分配到群组。伪代码:
int nextGroup = noOfGroups - 1
while players is not empty
player = random entry in players
remove player from players
add player to group[nextGroup]
nextGroup--
if(nextGroup < 0)
nextGroup = noOfGroups - 1
loop
答案 1 :(得分:1)
while
array
的长度
unshift
数组使用组{/ 1}}的条件
length
答案 2 :(得分:1)
我们首先发明一个数组方法来正确地改组数组。之后我们的工作很简单。我想以下应该这样做。
Array.prototype.shuffle = function(){
var i = this.length,
j,
tmp;
while (i > 1) {
j = Math.floor(Math.random()*i--);
tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
return this;
};
function groupPlayers(a,n){
var result = [],
remnants = a.shuffle().splice(-(a.length % n) || a.length); // the ones out in the cold
for (var i = 0, len = a.length; i < len; i += len/n ) result.push(a.slice(i,i + len/n));
return remnants.reduce((res,e,i,a) => (res[res.length-1-i].push(e),res),result); // finding a home for remnants
}
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
result = groupPlayers(arr,3);
console.log(result);