Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created July 23, 2014 13:04
Show Gist options
  • Save Mottie/ab2f026e6624e2733c1f to your computer and use it in GitHub Desktop.
Save Mottie/ab2f026e6624e2733c1f to your computer and use it in GitHub Desktop.
/* Shuffle
Modified Fisher-Yates shuffle ( original from http://bost.ocks.org/mike/shuffle/ )
to allow not shuffling specifically mapped array elements
Example:
var arry = [ 'aardvark', 'bison', 'cheeta', 'dingo', 'elephant', 'fawn', 'giraffe', 'hippo' ],
// don't shuffle 'bison' or 'elephant'
map = [ '', false, '', '', false ];
shuffle( arry, map ); // ["fawn", "bison", "dingo", "giraffe", "elephant", "hippo", "cheeta", "aardvark"]
shuffle( arry, map ); // ["aardvark", "bison", "hippo", "dingo", "elephant", "cheeta", "giraffe", "fawn"]
shuffle( arry, map ); // ["giraffe", "bison", "hippo", "dingo", "elephant", "aardvark", "fawn", "cheeta"]
shuffle( arry, map ); // ["aardvark", "bison", "cheeta", "giraffe", "elephant", "fawn", "dingo", "hippo"]
*/
shuffle = function (array, map) {
var swap, random,
index = array.length;
// While there remain elements to shuffle...
while (index > 0) {
// Pick a remaining element...
random = Math.floor(Math.random() * index);
if (map[index - 1] === false) {
index--;
}
// skip elements that are mapped to false
if (map[index - 1] !== false && map[random] !== false) {
// And swap it with the current element
index--;
swap = array[index];
array[index] = array[random];
array[random] = swap;
}
}
return array;
};
@Mottie
Copy link
Author

Mottie commented Jul 23, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment