javascript Javascript中没有欺骗的随机数生成器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3796786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:16:13  来源:igfitidea点击:

Random number generator without dupes in Javascript?

javascriptrandom

提问by Vic

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?

我需要帮助编写一些代码,这些代码将从 12 个数字的数组中创建一个随机数并打印 9 次而不会被欺骗。这对我来说很难完成。有任何想法吗?

回答by Jacob Relkin

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

回答by JoshD

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.

最有效和最有效的方法是洗牌你的数字,然后打印其中的前九个。使用好的 shuffle 算法。Thilo 建议的结果会很差。 看这里。

EditHere's a brief Knuth Shuffle algorithm example:

编辑这是一个简短的 Knuth Shuffle 算法示例:


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

回答by Thilo

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.

然后您可以打印前九个数组元素,这些元素将按随机顺序排列,不再重复。

回答by Randy the Dev

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.

其他方法包括对数组进行混洗、从数组中删除使用过的元素或将使用过的元素移动到数组的末尾。

回答by Sudhir Bastakoti

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

回答by cologne

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

这是在 min 和 max 之间获取随机数而没有重复的通用方法:

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