Shuffling Arrays with JavaScript
The Fisher-Yates shuffle algorithm offers an effective method for shuffling arrays in JavaScript. By randomly swapping elements, it guarantees that each possible ordering has an equal chance of occurring.
Algorithm Implementation
The Fisher-Yates shuffle algorithm can be implemented as follows:
function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; }
This algorithm iterates through the array in reverse order, swapping each element with a random element ahead of it in the array. The resulting array is shuffled due to the random nature of the swaps.
Usage
The shuffle function can be used to shuffle an array using the following syntax:
var myArray = ['1','2','3','4','5','6','7','8','9']; shuffle(myArray);
ES6 Version
The Fisher-Yates algorithm has been optimized in ES6:
function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }
Implementation Prototype
This algorithm can be implemented as an array prototype method to facilitate direct shuffling of arrays:
Object.defineProperty(Array.prototype, 'shuffle', { value: function() { for (let i = this.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i 1)); [this[i], this[j]] = [this[j], this[i]]; } return this; } });
This implementation allows arrays to be shuffled using the arr.shuffle() syntax.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3