## Big O Forum View Course » View Exercise

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);
``````

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

Tatjana Seketa over 5 years ago

Thanks! It worked.

Sofia Perwallius about 4 years ago

Thanks a lot

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`.