最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Random number generator without dupes in Javascript? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Sep 26, 2010 at 6:17 Yi Jiang 50.1k16 gold badges138 silver badges136 bronze badges asked Sep 26, 2010 at 6:12 VicVic 231 gold badge1 silver badge3 bronze badges 0
Add a comment  | 

8 Answers 8

Reset to default 9

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));
}

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]);
  }
}

Try this once:

//Here o is the array;
var testArr = [6, 7, 12, 15, 17, 20, 21];
    shuffle = function(o){ //v1.0
                        for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
                        return o;
                };
shuffle(testArr);

This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.

var tempArray = new Array(12),i,r;
for (i=0;i<9;i++)
    {
    r = Math.floor(Math.random()*12);    // Get a random index
    if (tempArray[r] === undefined)      // If the index hasn't been used yet
        {
        document.write(numberArray[r]);  // Display it
        tempArray[r] = true;             // Flag it as have been used
        }
    else                                 // Otherwise
        {
        i--;                             // Try again
        }
    }

Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.

If I understand you correctly, you want to shuffle your array.

Loop a couple of times (length of array should do), and in every iteration, get two random array indexes and swap the two elements there. (Update: if you are really serious about this, this may not be the best algorithm).

You can then print the first nine array elements, which will be in random order and not repeat.

Here is a generic way of getting random numbers between min and max without duplicates:

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

function getRandomIntNoDuplicates(min, max, DuplicateArr) {
    var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
    if (DuplicateArr.length > (max-min) ) return false;  // break endless recursion
    if(!inArray(DuplicateArr, RandomInt)) {
       DuplicateArr.push(RandomInt); 
       return RandomInt;
    }
    return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
}

call with:

var duplicates  =[];
for (var i = 1; i <= 6 ; i++) { 
    console.log(getRandomIntNoDuplicates(1,10,duplicates));
}
const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
for(var i = 1 ; i < 10; i++){
    result = nums[Math.floor(Math.random()*nums.length)];
    const index = nums.indexOf(result);
    nums.splice(index, 1);
    console.log(i+' - '+result);
}

var nums = [1,2,3,4,5,6,7,8,9];
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 = 1; i < 9; i++) {
    console.log(get_rand(nums));
}

发布评论

评论列表(0)

  1. 暂无评论