Jak randomizovat/zamíchat pole v JavaScriptu [Příklady]

Tento článek vám ukáže několik jednoduchých i složitých způsobů, jak náhodně/zamíchat pole v JavaScriptu.

Rychlý a špinavý způsob náhodného rozdělení pole

Pokud se příliš nezajímáte o související pravděpodobnosti, tento kód je rychlý způsob, jak znáhodnit obsah pole:

// Function to return a shuffled copy of a given array
function shuffle(array) {
    var shuffled = [...array]; // Make a copy of the array to be shuffled so that the original is not altered by the sort() function below
    shuffled.sort(() => Math.random() - 0.5); // Sort the array using the sort() method with random input from Math.random()
    return shuffled; // Return the shuffled copy of the array
}

Používá se takto:

var fruitArray = ['peach', 'apple', 'banana', 'pear']; // Create an array of fruit
shuffledFruit = shuffle(fruitArray); // Shuffle it and assign the returned value to a new variable
console.log(shuffledFruit); // Will print the shuffled copy of the array

Tato metoda však není skutečně náhodné – je to slabina v sort() metoda implementovaná v JavaScriptu. The Math.random() funkce také není úplně náhodné.

Tato metoda je však dost dobrá pro základní scénáře, kde se příliš nestaráte o efektivitu nebo náhodnost, jako je náhodné pořadí sezení pro studenty ve třídě nebo barvy hráčů ve hře. Na druhou stranu, pokud píšete loterijní program nebo pracujete v jiném scénáři, kde záleží na pravděpodobnosti a spravedlnosti, budete chtít použít jinou metodu.

Moderní Fisher-Yates Shuffle v JavaScriptu (správná cesta)

Fisher-Yates je metoda náhodného uspořádání/promíchání sekvence položek, která je skutečně náhodné. Je to nejlepší způsob, jak to udělat, ale vyžaduje trochu dodatečného kódování, protože JavaScript nemá žádnou vestavěnou implementaci.

Pokud jde o proč je to lepší? Doporučuji prostudovat si článek na Wikipedii, kde najdete správné vysvětlení. Ale budu se držet kódu:

// Function to return a shuffled copy of a given array (Fisher-Yates)
function shuffle(array) {
    var shuffled = [...array]; // Make a copy of the array to be shuffled so the original is not altered
    for (var i = shuffled.length - 1; i > 0; i--) { // Loop through each index (position) in the array
        var j = Math.floor(Math.random() * (i + 1)); // Pick an index randomly from the array
        var temp = shuffled[i]; // Store the value at the current index
        shuffled[i] = shuffled[j]; // Replace the value at the current position with the one at the randomly picked index
        shuffled[j] = temp; // Replace the value at the randomly picked index with the one which was at the current index (swapping them!)
    }
    return shuffled; // Return the shuffled array
}

Používá se stejným způsobem jako předchozí příklad:

var fruitArray = ['peach', 'apple', 'banana', 'pear']; // Create an array of fruit
shuffledFruit = shuffle(fruitArray); // Shuffle it and assign the returned value to a new variable
console.log(shuffledFruit); // Will print the shuffled copy of the array


No