0

Suppose I have 16 numbers, range 0 to 15. They sit in an array. What I want to achieve is the following arrays:

  1. Array with 3 random numbers.
  2. Array with 2 random numbers.
  3. Array with 3 random numbers.
  4. Array with 2 random numbers.
  5. Array with 2 random numbers.
  6. Array with 3 random numbers.

The numbers from the, what I will call, masterarray, can only be used once. So array x holds 1, 5 and 7, array y holds 2, 9 (these should be totally random).

I understand that I can get and remove items from an array using indexOf and splice. But how would I go about getting the random numbers from the array while also removing them from this list?

A foreach wouldn't go as the array gets altered in this process. Same goes for a for-loop, to my understanding.

How can I achieve this?

Matthijs
  • 3,162
  • 4
  • 25
  • 46
  • 3
    You'd shuffle the original array and then use `pop()` to fill the new arrays. See: http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript. – James Donnelly Dec 09 '14 at 14:47
  • Thanks a bunch! I will give that a go :) I hadn't thought about going at it from a shuffling angle! – Matthijs Dec 09 '14 at 14:49

1 Answers1

0

here's a non-shuffle approach...

var master = [], arr1=[], arr2=[], arr3=[], arr4=[], arr5=[], arr6=[], i=1;

for(i; i<16;i++){  // populating "master" array
master.push(i); 
}


while(master.length>0){
var num =master.splice(Math.floor(Math.random()*master.length),1)[0];
if (master.length>11){
arr1.push(num);
continue;
}
if(master.length>9){
arr2.push(num);
continue;
}
if(master.length>6){
arr3.push(num);
continue;
}
if(master.length>4){
arr4.push(num);
continue;
}
if(master.length>2){
arr5.push(num);
continue;
}
else {
arr6.push(num);
}
}
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
console.log(arr5);
console.log(arr6);
lucas
  • 1,485
  • 13
  • 22