Jose Miguel Ledón
Jose Miguel Ledón

Reputation: 309

divide an array of numbers into subarrays in equally parts and randomized from a given integer

to make it clearer I have an array of player ids and I want to divide into X number of groups equally and randomly, but when the number is odd the group 1 need to be the subarray with the small number of parts: like this example:

I cases when the number is even is easier but i don't know how to achieve this case. I need some help to know how to.

Upvotes: 0

Views: 439

Answers (3)

Redu
Redu

Reputation: 26161

We start with inventing an array method to properly shuffle the arrays. Afterwards our job is simple. I guess the following should do it.

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

Upvotes: 1

Rayon
Rayon

Reputation: 36599

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
var i = arr.length;
var partLen = i / 3;
var parentArr = [],
  temp = [];

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
var shuffled = shuffle(arr);
while (i--) {
  if (temp.length >= partLen) {
    parentArr.unshift(temp);
    temp = [];
  }
  temp.push(shuffled[i]);
}
if (temp.length) {
  parentArr.unshift(temp);
  temp = [];
}
console.log(JSON.stringify(parentArr, null, 4));

Upvotes: 1

Nico Schertler
Nico Schertler

Reputation: 32607

Just pick players sequentially and assign them to groups. Pseudo code:

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

Upvotes: 2

Related Questions