Last active
March 4, 2020 14:17
-
-
Save stgogm/5462235 to your computer and use it in GitHub Desktop.
This is just for shuffling an array. It gives you a more shuffled array than using sort(). I got it from http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/ - I'm keeping it here just for backup purposes.
This file contains hidden or 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
| /** | |
| * Shuffles array in place. | |
| * | |
| * @param {Array} a items The array containing the items. | |
| */ | |
| function shuffle(a) { | |
| var j, x, i; | |
| for (i = a.length; i; i--) { | |
| j = Math.floor(Math.random() * i); | |
| x = a[i - 1]; | |
| a[i - 1] = a[j]; | |
| a[j] = x; | |
| } | |
| } | |
| /** | |
| * Shuffles array in place. ES6 version. | |
| * | |
| * @param {Array} a items The array containing the items. | |
| */ | |
| function shuffle(a) { | |
| for (let i = a.length; i; i--) { | |
| let j = Math.floor(Math.random() * i); | |
| [a[i - 1], a[j]] = [a[j], a[i - 1]]; | |
| } | |
| } | |
| /** | |
| * Shuffles a copy of an array and returns it. | |
| * | |
| * @param {Array} array The array to copy and shuffle. | |
| * | |
| * @returns {Array} The shuffled array. | |
| * | |
| * @see https://bost.ocks.org/mike/shuffle/ | |
| */ | |
| function shuffle(array) { | |
| const a = [...array]; | |
| let m = a.length; | |
| let t; | |
| let i; | |
| // While there remain elements to shuffle... | |
| while (m) { | |
| // Pick a remaining element... | |
| i = Math.floor(Math.random() * m--); | |
| // And swap it with the current element... | |
| t = a[m]; | |
| a[m] = a[i]; | |
| a[i] = t; | |
| } | |
| return a; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment