Cómo aleatorizar/mezclar una matriz en JavaScript [Ejemplos]

Este artículo le mostrará algunas formas, tanto fáciles como complejas, de aleatorizar/mezclar una matriz en JavaScript.

La forma rápida y sucia de aleatorizar una matriz

Si no está demasiado preocupado por las probabilidades involucradas, este código es una forma rápida de aleatorizar el contenido de una matriz:

// 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
}

Se usa así:

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

Este método, sin embargo, no es verdaderamente random:es una debilidad en sort() método tal como se implementa en JavaScript. El Math.random() la función tampoco es totalmente aleatorio.

Sin embargo, este método es suficientemente bueno para escenarios básicos en los que no le importa demasiado la eficiencia o la aleatoriedad, como aleatorizar el orden de los asientos para los estudiantes en una clase o los colores de los jugadores en un juego. Por otro lado, si está escribiendo un programa de lotería o está trabajando en algún otro escenario donde las probabilidades y la equidad importan, querrá usar un método diferente.

El Fisher-Yates Shuffle moderno en JavaScript (la forma correcta)

Fisher-Yates es un método para aleatorizar/mezclar una secuencia de elementos que es verdaderamente al azar. Es la mejor manera de hacerlo, pero requiere un poco de codificación adicional ya que JavaScript no tiene una implementación integrada.

En cuanto a por qué ¿es mejor? Recomiendo consultar el artículo de Wikipedia para obtener una explicación adecuada. Pero me ceñiré al código:

// 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
}

Se usa de la misma manera que el ejemplo anterior:

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