javascriptrandom

Random number generator without dupes in Javascript?


I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas?


Solution

  • 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++) {
        console.log(get_rand(nums));
    }