Skip to content

Instantly share code, notes, and snippets.

@alexhawkins
Created August 21, 2014 02:28
Show Gist options
  • Select an option

  • Save alexhawkins/99e91c50d5e3e51c2464 to your computer and use it in GitHub Desktop.

Select an option

Save alexhawkins/99e91c50d5e3e51c2464 to your computer and use it in GitHub Desktop.
Shuffle a Deck of Cards
var shuffle = function(arr) {
var rand, temp;
//loop through array and swap out value at random position
//with value at iteration position of array
for (var i = 0; i < arr.length; i++) {
//generate random number between 0 and length of array.
rand = Math.floor(Math.random() * arr.length);
temp = arr[i]; //store value of arr[i] to swap later
arr[i] = arr[rand]; //set arr[i] to random position value
arr[rand] = temp; //replace with temp
}
return arr;
};
//tests
console.log(shuffle([1, 2, 3, 4, 5, 6, 73, 13, 20, 32, 33, 14, 12, 24]));
//[ 3, 14, 4, 32, 12, 1, 2, 13, 73, 33, 24, 6, 20, 5 ]
//[ 20, 4, 2, 1, 3, 5, 24, 73, 32, 12, 14, 33, 13, 6 ]
//[ 2, 5, 24, 1, 14, 32, 33, 20, 3, 12, 13, 4, 73, 6 ]
//[ 3, 5, 2, 1, 33, 4, 20, 6, 14, 73, 32, 24, 12, 13 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment