Skip to content

Instantly share code, notes, and snippets.

@johntran
Last active August 29, 2015 14:27
Show Gist options
  • Save johntran/5d33863e42720b81a515 to your computer and use it in GitHub Desktop.
Save johntran/5d33863e42720b81a515 to your computer and use it in GitHub Desktop.
/** Given an array, guarantee
* each element is shuffled once
* O(n) runtime
*/
Array.prototype.shuffle = function() {
var remainingElements = this.length;
var helper;
var target;
while (remainingElements) {
target = Math.floor(Math.random()*remainingElements--);
helper = this[remainingElements];
this[remainingElements] = this[target];
this[target] = helper;
}
}↵
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment