This problem was asked by Tencent.
How would you implement a shuffle() ?
Shuffle the array, it may be [1, 3, 2, 4], but it should modify the array inline to generate a randomly picked permutation at the same probability.
Example
[1, 2, 3, 4].shuffle()
Solution
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function shuffle() {
let i = this.length - 1;
while (i) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
i--;
}
return this;
};
}
This works by:
- Checking if Array.prototype.shuffle() already exists
- If not, adding a shuffle() method to the Array prototype
- The shuffle() method:
- Loops from the array length down to 0
- Picks a random index between 0 and i
- Swaps the current element (i) with the random element (j)
- This shuffling procedure is performed in place on the array
- The shuffled array is returned
This polyfill implements a simple shuffle algorithm to randomly rearrange the elements of an array.
Top comments (0)