Random number generator without dupes in Javascript?

Solution 1:

var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];

function in_array(array, el) {
   for(var i = 0 ; i < array.length; i++) 
       if(array[i] == el) return true;
   return false;
}

function get_rand(array) {
    var rand = array[Math.floor(Math.random()*array.length)];
    if(!in_array(gen_nums, rand)) {
       gen_nums.push(rand); 
       return rand;
    }
    return get_rand(array);
}

for(var i = 0; i < 9; i++) {
    document.write(get_rand(nums));
}

Solution 2:

The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.

Edit Here's a brief Knuth Shuffle algorithm example:


void shuffle(vector<int> nums)
{
  for (int i = nums.size()-1; i >= 0; i--)
  {
    // this line is really shorthand, but gets the point across, I hope.
    swap(nums[i],nums[rand()%i]);
  }
}