Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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