A New Chicken
A New Chicken

Reputation: 703

Shuffle an array in JavaScript?

I need an 2d array [9,16] with 144 numbers from 1->36 in random order (so each number is repeated 4 times).

Upvotes: 0

Views: 1332

Answers (3)

atk
atk

Reputation: 9314

How's about:

var source = array();
var shuffled = array();

for(var i=0;i<4;i++)
{
  for(var j=0; j<36;j++)
  {
    source[i*j] = j+1;
  }
}

while( source.length > 0 )
{
  var index = Math.floor(Math.random()*source.length);
  var element = source.splice(index,1);
  shuffled.push(element);
}

Upvotes: 0

Mark Elliot
Mark Elliot

Reputation: 77034

Something like:

sourcearr = array();
for(i = 0; i < 36; i++){
  for(j = 0; j < 4; j++){
      sourcearr[i+j] = i;
   }
}

sourcearr = shuffle(sourcearr)

k = 0;
myrandarr = array();
for(i = 0; i < 9; i++){
    myrandarr[i] = array();
    for(j = 0; j < 16; j++){
        myrandarr[i][j] = sourcearr[k++];
    }
}

where you use shuffle.

Upvotes: 4

Jim Garrison
Jim Garrison

Reputation: 86764

Assuming you don't care about the distribution, just store the results of

Math.floor(Math.random()*36) + 1

for each element of the array

Upvotes: 2

Related Questions