Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.random in regards to arrays

I am confused about how arrays work in tandem with functions like Math.random(). Since the Math.random() function selects a number greater than or equal to 0 and less than 1, what specific number is assigned to each variable in an array? For example, in the code below, what number would have to be selected to print out 1? What number would have to be selected to print out jaguar?

var examples= [1, 2, 3, 56, "foxy", 9999, "jaguar", 5.4, "caveman"];
var example= examples[Math.round(Math.random() * (examples.length-1))];
console.log(example);

Is each element in an array assigned a position number equal to x/n (x being the position number relative to the first element and n being the number of elements)? Since examples has 9 elements, would 1 be at position 1/9 and would 9999 be at position 6/9?

like image 225
Darien Springer Avatar asked May 30 '15 05:05

Darien Springer


2 Answers

Math.round() vs. Math.floor()

The first thing to note: Math.round() is never the right function to use when you're dealing with a value returned by Math.random(). It should be Math.floor() instead, and then you don't need that -1 correction on the length. This is because Math.random() returns a value that is >= 0 and < 1.

This is a bit tricky, so let's take a specific example: an array with three elements. As vihan1086's excellent answer explains, the elements of this array are numbered 0, 1, and 2. To select a random element from this array, you want an equal chance of getting any one of those three values.

Let's see how that works out with Math.round( Math.random() * array.length - 1 ). The array length is 3, so we will multiply Math.random() by 2. Now we have a value n that is >= 0 and < 2. We round that number to the nearest integer:

If n is >= 0 and < .5, it rounds to 0.
If n is >= .5 and < 1.5, it rounds to 1.
If n is >= 1.5 and < 2, it rounds to 2.

So far so good. We have a chance of getting any of the three values we need, 0, 1, or 2. But what are the chances?

Look closely at those ranges. The middle range (.5 up to 1.5) is twice as long as the other two ranges (0 up to .5, and 1.5 up to 2). Instead of an equal chance for any of the three index values, we have a 25% chance of getting 0, a 50% chance of getting 1, and a 25% chance of 2. Oops.

Instead, we need to multiply the Math.random() result by the entire array length of 3, so n is >= 0 and < 3, and then floor that result: Math.floor( Math.random() * array.length ) It works like this:

If n is >= 0 and < 1, it floors to 0.
If n is >= 1 and < 2, it floors to 1.
If n is >= 2 and < 3, it floors to 2.

Now we clearly have an equal chance of hitting any of the three values 0, 1, or 2, because each of those ranges is the same length.

Keeping it simple

Here is a recommendation: don't write all this code in one expression. Break it up into simple functions that are self-explanatory and make sense. Here's how I like to do this particular task (picking a random element from an array):

// Return a random integer in the range 0 through n - 1
function randomInt( n ) {
    return Math.floor( Math.random() * n );
}

// Return a random element from an array
function randomElement( array ) {
    return array[ randomInt(array.length) ];
}

Then the rest of the code is straightforward:

var examples = [ 1, 2, 3, 56, "foxy", 9999, "jaguar", 5.4, "caveman" ];
var example = randomElement( examples );
console.log( example );

See how much simpler it is this way? Now you don't have to do that math calculation every time you want to get a random element from an array, you can simply call randomElement(array).

like image 122
Michael Geary Avatar answered Oct 21 '22 03:10

Michael Geary


They're is quite a bit happening so I'll break it up:

Math.random

You got the first part right. Math.random will generate a number >= 0 and < 1. Math.random can return 0 but chances are almost 0 I think it's like 10^{-16} (you are 10 billion times more likely to get struck by lightning). This will make a number such as:

0.6687583869788796

Let's stop there for a second

Arrays and their indexes

Each item in an array has an index or position. This ranges from 0 - infinity. In JavaScript, arrays start at zero, not one. Here's a chart:

[ 'foo', 'bar', 'baz' ]

Now the indexes are as following:

name | index
-----|------
foo  | 0
bar  | 1
baz  | 2

To get an item from it's index, use []:

fooBarBazArray[0]; // foo
fooBarBazArray[2]; // baz

Array length

Now the array length won't be the same as the largest index. It will be the length as if we counted it. So the above array will return 3. Each array has a length property which contains it's length:

['foo', 'bar', 'baz'].length; // Is 3

More Random Math

Now let's take a look at this randomizing thing:

Math.round(Math.random() * (mathematics.length-1))

They're is a lot going on. Let's break it down:

Math.random()

So first we generate a random number.

* mathematics.length - 1

The goal of this random is to generate a random array index. We need to subtract 1 from the length to get the highest index.

First Part conclusions

This now gives us a number ranging from 0 - max array index. On the sample array I showed earlier:

Math.random() * (['foo', 'bar', 'baz'].length - 1)

Now they're is a little problem:

This code makes a random number between 0 and the length. That means the -1 shouldn't be there. Let's fix this code:

Math.random() * ['foo', 'bar', 'baz'].length

Running this code, I get:

2.1972009977325797
1.0244733088184148
0.1671080442611128
2.0442249791231006
1.8239217158406973

Finally

To get out random index, we have to make this from an ugly decimal to a nice integer: Math.floor will basically truncate the decimal off.

Math.floor results:

2
0
2
1
2

We can put this code in the [] to select an item in the array at the random index.

More Information / Sources

  • Random Numbers
  • More solutions
like image 31
Downgoat Avatar answered Oct 21 '22 05:10

Downgoat