Last active
December 22, 2020 07:58
-
-
Save sungchuni/2fc1d1af31274535a3b4d64453944e73 to your computer and use it in GitHub Desktop.
simple implementation fisher-yates 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
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; | |
} |
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
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; | |
} |
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
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