BFE.dev is like a LeetCode for Front End developers. I’m using it to practice my skills.

This article is about the coding problem BFE.dev#8. can you shuffle() an array?

## Analysis

The goal is to shuffle an array, seems pretty easy. Since shuffle is choose one of the all possible permutations, so we can choose the item one by one randomly from rest possible positions.

```
function shuffle(arr) {
for (let i = 0; i < arr.length; i++) {
const j = i + Math.floor(Math.random() * (arr.length - i))
;[arr[i], arr[j]] = [arr[j], arr[i]]
}
}
```

## Code Not working

```
function shuffle(arr) {
for (let i = 0; i < arr.length; i++) {
const j = Math.floor(Math.random() * arr.length)
;[arr[i], arr[j]] = [arr[j], arr[i]]
}
}
```

Above code looks working but actually not. It loops all the positions and randomly swaps with another.

Suppose we have an array of [1,2,3,4].

Let's look at number 1. The first step is to swap 1 with all 4 positions, chance is high that it is moved to the positions other than itself and later it is traversed and swapped again.

Now let's look at number 4. It is last number to be traversed, and it might be also swapped before its turn and never be traversed again.

So 1 and 4 have different chances of be swapped, 4 is obviously lower, so the result array is not randomly shuffled.

## Passed

Here is my video explaining: https://www.youtube.com/watch?v=FpKnR7RQaHM

Hope it helps, you can have a try at here

## Top comments (0)