Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active April 1, 2020 03:43
Show Gist options
  • Save dfkaye/3bcd809fee40132c5387c241b42164c1 to your computer and use it in GitHub Desktop.
Save dfkaye/3bcd809fee40132c5387c241b42164c1 to your computer and use it in GitHub Desktop.
Better Fisher-Yates array shuffle in ES5
// 28 March 2020
// Better Fisher-Yates shuffle in ES5
// Supersedes https://gist.github.com/dfkaye/36a4cd28c91d8ee1febb92c1b2b57e04
// Updated 31 March 2020: use Array.from(); fix test sorting; rename at, from, and to variables.
function shuffle(array) {
var result = Array.from(array);
/*
* This version mutates the array being processed.
* Considered generally unsafe practice, done here
* for variable lookup speed within the function scope.
*/
result.forEach(function(v, i, arr, at, from, to) {
// Create indexes from and to
at = arr.length - i;
from = Math.floor(Math.random() * at);
to = at - 1;
// Swap values from and to
v = arr[to];
arr[to] = arr[from];
arr[from] = v;
});
return result;
}
/* Test it out */
var source = Array.from(Array(10)).map((v,i) => i + 1);
Array.from(Array(10))
.map(() => shuffle(source))
.sort((a, b) => Number(a.join('')) - Number(b.join('')))
.forEach(result => console.log(result.join(' ')));
/*
1 2 5 4 10 3 6 7 8 9
2 1 3 4 9 10 5 6 8 7
4 10 5 8 1 6 9 3 2 7
4 10 5 8 9 2 6 1 3 7
4 5 1 8 3 9 2 10 6 7
8 2 6 9 7 4 10 5 3 1
8 7 10 9 1 2 5 6 4 3
9 3 8 6 5 1 4 7 2 10
9 4 3 2 5 8 10 6 1 7
9 8 7 1 4 6 10 5 3 2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment