Created
July 23, 2014 13:04
-
-
Save Mottie/ab2f026e6624e2733c1f to your computer and use it in GitHub Desktop.
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
/* 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: http://jsfiddle.net/Mottie/rU3mq/