This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Big O Forum

View Course » View Exercise

3347 points
527677fcabf82128d50042ae_584313652
Submitted by
Tatjana Seketa
over 4 years ago

SOMEONE PLEASE EXPLAIN!

Here is my code:

var array = ["P", "e", "a", "n", "u", "t", "s", "R", "o", "c", "k"];

var out = Math.random(array);
console.log(out);

Why does this not work?!?! Someone please help!


3 votes

permalink

Try this.
var out = array[Math.floor(Math.random()*array.length)];

1030 points
50eabe3480754908fc007972_431295236
Submitted by
Roeland
over 4 years ago

2 Comments

527677fcabf82128d50042ae_584313652 Tatjana Seketa over 4 years ago

Thanks! It worked.

533b22568c1ccc6c0d00409e_910858883 Sofia Perwallius about 3 years ago

Thanks a lot


0 votes

permalink

Old topic; yes. Hopefully the explanation can help somebody else with the same trouble.

It doesn't work because you are giving Math.random() an input parameter (it has no input).
When console.log(out) is called, it just prints a random number to the console.

Roeland's algorithm is one solution, and I would guess that it's the most popular.

First we declare out and assign array to it. Of course, we need to be specific about which item, so now the question is array[???].

We can't go without Math.random(), so we'll start from there.

  • array[Math.random()]

Next we add array.length.

  • array[Math.random() * array.length]

This will generate a random number from 0 to array.length, which is pretty cool. However, we still have to round Math.random() into whole numbers.

  • array[Math.floor(Math.random() * array.length)]

Math.floor() will do the trick, plus it preserves our index at 0, as opposed to using Math.ceiling.

619 points
593ad59e2524c8aa5000029d_27875226
Submitted by
eth0
about 4 years ago