Created
July 19, 2015 11:02
-
-
Save JayMc/72ff2c5534560a0ae4f6 to your computer and use it in GitHub Desktop.
An improved shuffle algorithm: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
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
function fisherYatesShuffle(array) { | |
var currentIndex = array.length | |
, temporaryValue | |
, randomIndex | |
; | |
// While there remain elements to shuffle... | |
while (0 !== currentIndex) { | |
// Pick a remaining element... | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
// And swap it with the current element. | |
temporaryValue = array[currentIndex]; | |
array[currentIndex] = array[randomIndex]; | |
array[randomIndex] = temporaryValue; | |
} | |
return array; | |
} | |
var randomChars = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m']; | |
randomChars = fisherYatesShuffle(randomChars) | |
var randomString; | |
for (var i = 0; i< 6; i++) { | |
randomString = randomString+randomChars[i]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment