Home >Web Front-end >JS Tutorial >How Can I Efficiently Shuffle an Array in JavaScript Using the Fisher-Yates Algorithm?

How Can I Efficiently Shuffle an Array in JavaScript Using the Fisher-Yates Algorithm?

DDD
DDDOriginal
2024-12-27 21:24:17435browse

How Can I Efficiently Shuffle an Array in JavaScript Using the Fisher-Yates Algorithm?

Efficient Array Shuffling Using Fisher–Yates Algorithm

In JavaScript, array shuffling is a common operation often used in randomization or game development. To effectively shuffle an array, the popular Fisher–Yates algorithm provides an efficient approach.

Fisher–Yates Algorithm Implementation

The core principle behind this algorithm involves repeatedly swapping elements from the array with randomly selected elements. This process continues until all elements have been swapped. The following code implements this algorithm:

/**
 * Shuffles an array in place.
 * @param {Array} a Array containing the elements to be shuffled.
 */
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;
}

ES6 Version

In ES6, the code can be simplified using destructuring assignment:

/**
 * Shuffles an array in place. ES6 version.
 * @param {Array} a Array containing the elements to be shuffled.
 */
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;
}

Array Prototype Implementation

To enhance code readability, you can add the shuffle functionality as a prototype method for 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 allows you to simply call arr.shuffle() to shuffle an array named arr.

Example Usage

To utilize the shuffle function, you can provide an array of elements as input, such as:

let myArray = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
shuffle(myArray);

The shuffle function will randomly rearrange the elements in myArray. This function can be particularly useful in scenarios where you need randomized data or the shuffling of cards in a game.

The above is the detailed content of How Can I Efficiently Shuffle an Array in JavaScript Using the Fisher-Yates Algorithm?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn