views:

30

answers:

2

Hi,

I need to create a 2D array for some POC work.

The first value of the array needs to go up in single increments between the values 1 to 1000 and the second value needs to be a random number from values 1 to 50.

+3  A: 
var array = [];
for (var i = 1; i <= 1000; i++)
{
  array.push([i, 1 + Math.floor(Math.random() * 50)]);
}

To explain how we end up with a random number between 1 and 50:

Math.random() generates a random floating point number r where 0 ≤ r < 1. Thus, multiplying that by 50 will result in a number s where 0 ≤ s < 50. Then we use Math.floor(), which rounds a decimal down to the nearest integer (so the result will be an integer between 0 and 49 inclusive). Adding 1 to that will give the desired result -- a random integer between 1 and 50.

Daniel Vandersluis
This generates a syntax error?
RyanP13
@Ryan sorry, I fixed it. That's what happens when I code in a textbox while working in multiple languages at once ;)
Daniel Vandersluis
+1  A: 
var array = [];
for (var i = 1; i <= 1000; i++)
{
  array.push([i, Math.ceil(Math.random() * 50)]);
}

Personally I prefer to use Math.ceil and have it round up, rather than round it down and then add one.

kwah