How to shuffle an array
- Hank
- 03 Dec, 2024
In a small talk, one of my friends asked me, without searching or using AI, can you figure out how to shuffle an array in JavaScript?
Surprisingly, I couldn’t answer him immediately. I was thinking about the sort
method, but I couldn’t remember the exact implementation, and I even thought about using timestamp as seed to generate a random number.
After the talk, I figured out the answer in a very short time. Here is the code:
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
Fine, this code is written by AI and its so simple and obvious. And here is the code that I want to write:
const shuffle = (arr) => {
const len = arr.length;
for (let i = 0; i < len; i++) {
const randomIdx = Math.floor(Math.random() * len);
[arr[i], arr[randomIdx]] = [arr[randomIdx], arr[i]];
}
return arr;
}
And then AI tells me about the Fisher-Yates shuffle algorithm, which is the most efficient way to shuffle an array. Here is the code:
const shuffleFisherYates = (arr) => {
for (let i = arr.length - 1; i > 0; i--) {
const randomIdx = Math.floor(Math.random() * (i + 1));
[arr[i], arr[randomIdx]] = [arr[randomIdx], arr[i]];
}
return arr;
}
why it is more effective? Because
- compare with using sort function, it only needs to iterate through the array once, while the sort method may iterate multiple times
- compare with my implementation, mine always generates a random number which from 0 to the length of the array, while Fisher-Yates shuffle algorithm only generates a random number which from 0 to the current index of the array.
- compare with my implementation, mine always swaps the element with itself, while Fisher-Yates shuffle algorithm only swaps the element with the element that has not been swapped.
-EOF-