Skip to content

Instantly share code, notes, and snippets.

@webbower
Created December 2, 2017 22:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webbower/8d19b714ded3ec53d1d7ed32b79fdbac to your computer and use it in GitHub Desktop.
Save webbower/8d19b714ded3ec53d1d7ed32b79fdbac to your computer and use it in GitHub Desktop.
Durstenfeld shuffle
// 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]];
}
}
@queviva
Copy link

queviva commented Jul 14, 2022

I think the ES6 version of that could be just one line; also, I don't think it needs to run in reverse

this:

const durstenshuffeld = (v, r=[...v]) => r.map((x, i, _,  j = ~~(Math.random() * (r.length - i)) + i ) => ([x, r[j]] = [r[j], x], x));

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:

    const yacht = (v, r=[...v]) => v.map(() =>
        r.splice(~~(Math.random() * r.length), 1)[0]
    );

is a single line of unbiased, immuted, naive shuffling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment