Last active
August 29, 2015 14:11
-
-
Save jabney/018feaa6b115b386260e to your computer and use it in GitHub Desktop.
Shuffle an array in place so that the positions of its values are random
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
// shuffle.js © 2014 James Abney http://github.com/jabney | |
(function(ex) { | |
'use strict'; | |
// Export shuffle to 'random' namespace. | |
var random = ex.random || (ex.random = Object.create(null)); | |
// Shuffle an array in place so that the positions of its values are random. | |
random.shuffle = function shuffle(a) { | |
var i, r, tmp, len = a.length; | |
for (i = 0; i < len; i++) { | |
r = i + Math.floor((len - i) * Math.random()); | |
tmp = a[i]; | |
a[i] = a[r]; | |
a[r] = tmp; | |
} | |
return a; | |
} | |
})(typeof exports !== 'undefined' && exports || this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment