Created
March 25, 2013 00:56
-
-
Save HTMLToronto/5234280 to your computer and use it in GitHub Desktop.
Sample randomization script. Please note that this is not something you should use in your production code. The randomization here is by far not the most efficient manner to randomize something. It is intended to demonstrate an extreme.
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
/* | |
* Create a shuffle array method returning the new shuffled array instead of effecting the original | |
*/ | |
Array.prototype.shuffle = function () { | |
for (var i = this.length - 1; i > 0; i--) { | |
var randomIndex = Math.floor(Math.random() * (i + 1)); | |
var tmp = this[i]; | |
this[i] = this[randomIndex]; | |
this[randomIndex] = tmp; | |
} | |
return this; | |
} | |
/* Return a Randomized Array Item | |
* Please note that there are FAR more effective and efficient ways to | |
* radomize and return a value from an array. This is only meant to | |
* give example of an extreme. | |
* | |
* @params arr myArray = The array item to randomly choose from | |
* int randCount = Times to randomly shuffle array | |
*/ | |
var randomize_array = function(myArray, randCount){ | |
// Set the base current count value | |
var currentCount = 0; | |
// Ensure that the random shuffle value is set | |
randCount = (typeof randCount == 'number') ? randCount : 1; | |
// Loop over for only the requested | |
while(currentCount < randCount){ | |
// Shuffle the array | |
myArray = myArray.shuffle(); | |
// Log the ransomization since most browsers will enumerate a duplicate log entry | |
console.log('Radomized'); | |
// Add 1 to the current count value | |
currentCount++; | |
} | |
// Return only the first value of the array | |
return myArray[0]; | |
}; | |
// Sample array item | |
my_array = [0, 1, 2, 3, 4]; | |
// Examples | |
// randomize_array(my_array, 5); | |
// randomize_array(my_array); | |
// randomize_array(my_array, 5 * 5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment