Skip to content

Instantly share code, notes, and snippets.

@sungchuni
Last active December 22, 2020 07:58
Show Gist options
  • Save sungchuni/2fc1d1af31274535a3b4d64453944e73 to your computer and use it in GitHub Desktop.
Save sungchuni/2fc1d1af31274535a3b4d64453944e73 to your computer and use it in GitHub Desktop.
simple implementation fisher-yates shuffle
function fisherYatesShuffle(array) {
const {length} = array;
array.forEach((value, index) => {
const rand = (index + Math.random() * (length - index)) | 0;
rand !== index && ([array[index], array[rand]] = [array[rand], value]);
});
return array;
}
function insideOutFisherYatesShuffle(array) {
const cloned = Array.from(array);
cloned.forEach((value, index) => {
const rand = (index && Math.random() * (index + 1)) | 0;
rand !== index && (cloned[index] = cloned[rand]), (cloned[rand] = value);
});
return cloned;
}
function fisherYatesShuffle(array) {
const [{length}, cloned] = [array, Array.from(array)];
cloned.forEach((value, index) => {
const rand = (index + Math.random() * (length - index)) | 0;
rand !== index && ([cloned[index], cloned[rand]] = [cloned[rand], value]);
});
return cloned;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment