Created
December 2, 2017 22:02
-
-
Save webbower/8d19b714ded3ec53d1d7ed32b79fdbac to your computer and use it in GitHub Desktop.
Durstenfeld shuffle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm | |
// https://stackoverflow.com/a/12646864/2684520 | |
// Pre-ES6 | |
/** | |
* Randomize array element order in-place. | |
* Using Durstenfeld shuffle algorithm. | |
*/ | |
function shuffleArray(array) { | |
for (var i = array.length - 1; i > 0; i--) { | |
var j = Math.floor(Math.random() * (i + 1)); | |
var temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
} | |
// ES6+ | |
function shuffleArray(array) { | |
for (let i = array.length - 1; i > 0; i--) { | |
let j = Math.floor(Math.random() * (i + 1)); | |
[array[i], array[j]] = [array[j], array[i]]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the ES6 version of that could be just one line; also, I don't think it needs to run in reverse
this:
will produce that same shuffle but without destroying the original array
and in ES6, I'm not even certain that inplace-shuffling is necessary; this implementation of the yacht-fisherman algorithm:
is a single line of unbiased, immuted, naive shuffling