views:

224

answers:

3

I need an 2d array [9,16] with 144 numbers from 1->36 in random order (so each number is repeated 4 times). I'm new at JS so can you give a hand, please. Thanks you.

+2  A: 

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

Jim Garrison
This won't repeat each number 4 times however.
jvenema
+4  A: 

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.

Mark E
I forgot to say that each number is repeated 4 times, it isn't just random.
A New Chicken
So there is nothing such as: Enumerable.Range(1,36)?
A New Chicken
Nope, not in JavaScript.
Eilon
A: 

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