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

## Big O Forum

# 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!**

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

.

## 2 Comments

Tatjana Seketa almost 5 years ago

Thanks! It worked.

Sofia Perwallius over 3 years ago

Thanks a lot