A function like this should work:
function addRandom(array, max)
{
if(array.length === max) {
return array;
}
var number = Math.round(Math.random() * (max - 1)) + 1;
if(array.indexOf(number) === -1) {
array.push(number);
return array;
}
return addRandom(array, max);
}
This takes your starting array and a maximum random integer. If the length of the array is already equal to the max integer, then the array is full and you won't ever find a new one. Otherwise, we make a new random number between 1 and the maximum.
To do this, we use Math.random()
(which returns a float from 0-1), multiply it by one less the maximum, round the result with Math.round()
, and add 1. If you say our max is 15, then this takes a float from 0 to 1 and multiplies it by 14 so you get 0 to 14. This is then rounded to an integer and we add 1 so we have a range of 1 to 15.
Finally, we use Array.indexOf()
(IE 9+) to see if the number already exists. If it doesn't, then we use Array.push()
to append the number and then return the new array. Otherwise, we will run the function again and generate a new number.
Use my JSFiddle to test this. I start with an array with length 5, and loop through it 15 times. You will see in the console that a random number is appended each time until every number is generated. An example out put is:
[4, 5, 1, 9, 6, 8]
[4, 5, 1, 9, 6, 8, 15]
[4, 5, 1, 9, 6, 8, 15, 2]
[4, 5, 1, 9, 6, 8, 15, 2, 3]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11, 10]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11, 10, 13]
[4, 5, 1, 9, 6, 8, 15, 2, 3, 12, 14, 7, 11, 10, 13]
[...]