Skip to content

Instantly share code, notes, and snippets.

@danieldunderfelt
Created December 3, 2014 12:21
Show Gist options
  • Save danieldunderfelt/69e3d37aad4d7eded1d8 to your computer and use it in GitHub Desktop.
Save danieldunderfelt/69e3d37aad4d7eded1d8 to your computer and use it in GitHub Desktop.
Generate an array with a random length, with distinct random values.
/**
*
* Usage: generateArray(10)
* Where 10 is the maximum allowed length (and value range) of the array.
*
* Example output: [5, 3, 9, 1, 0, 2]
*
*
*/
var generateArray = function(maxItems) {
var items = Math.floor(Math.random() * maxItems) + 1; // Change to reference maxItems if you want a static length
var arr = [];
for(var i = 0; i < items; i++) {
var isDifferent = false;
var randomNumber;
// This loop will try numbers until it generates one that doesn't already exist.
while(!isDifferent) {
if(arr.length === 0) isDifferent = true; // No need to do it more than once if the array is still empty
randomNumber = Math.floor(Math.random() * (maxItems - 1)) + 0; // Remove '-1' and change '0' to 1 if you don't want the values to be zero-indexed.
if(arr.indexOf(randomNumber) === -1) {
isDifferent = true;
}
}
arr.push(randomNumber);
}
return arr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment