# Chapter 19, Math.random I'm confused

Hello, I’m half way through the javascript book, it’s great so far but I am stuck at chapter 19 and wondered if anyone can help me.

When I look at the following code, I can see how Math.random can possibly generate a duplicate random number during the loop. When I run the code it actually works with no duplicate random number. Why is this?

function shuffle(input) {
for (let i = input.length - 1; i >= 0; i–)
{
let randomIndex = Math.floor(Math.random() * (i + 1));
let itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}

What makes you think you aren’t getting duplicates?

Something that’s potentially interesting about this code is that the random number is an index into the array, so swapping items at a random index never means that you get duplicate items in the array, merely the potential for reversed swaps.

It’s sort of like if you’re playing musical chairs with people running around randomly between chairs. Unless you have a machine that clones people, all the randomization in the order that people choose chairs isn’t going to result to duplicate people. The worst thing you can get is an uninteresting shuffle.

2 Likes

Thanks for your explanation, I get it now. Its just swapping the index based on a random Index number. It was confusing to get my head around it and now I understand it.
Thank you!

Glad the extra explanation helped; enjoy the rest of the book!

2 Likes

One thing that you may find interesting @kevin321 is this Random Number Frequency Visualizer that shows how often the same number gets hit

1 Like