将数组数组分成等分的子数组,并从给定的整数中随机化

时间:2016-08-28 02:54:05

标签: javascript arrays algorithm math

为了让它更清晰我有一个玩家ID数组,我想平均和随机地分成X个组,但是当数字是奇数时,组1需要是具有少量部分的子阵列:like这个例子:

  • 玩家ID:[1,2,3,4,5,6,7,8,9,10,11,12,13,14]
  • 团体数量:3
  • 预期结果:[14,12,2,1],[3,4,8,13,11],[5,6,7,9,10]

我的数字是偶数的情况更容易,但我不知道如何实现这种情况。我需要一些帮助才能知道如何做。

3 个答案:

答案 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)

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