javascript - 唯一随机数生成器 Javascript

标签 javascript random generator

我正在尝试制作一个宾果游戏来获得乐趣。我找了很多地方寻找独特的发电机,但似乎找不到。我试着自己做,但一旦它真的碰到一个相同的数字,它就会无限循环。我已经尝试了一个简单的代码,理论上应该可以工作,但由于某种原因,事情通过了。我能做什么!?

var bc = [];
for (var i = 0; i < 5; i++) {
  var r = Math.floor(Math.random()*20+1) + 0;
  if(!(r in bc)){
    bc.push(r);     
    }
    else
    {
    i--;
    }
}
____________________________________________
____________________________________________
____________________________________________
b1=0;
b2=0;
b3=0;
b4=0;
b5=0;
var bc = [b1,b2,b3,b4,b5]
var bnc = function(){
    var n = Math.floor(Math.random() * 5+1)+0;
    var n2 = Math.floor(Math.random() * 5+1)+0;
    b1 = n;
    var a1 = true;
    var as = false;
    while(a1){
        var c = n;
        if(c===b1||c===0 ||as!==false){
        c = n2;
        as=true;
        }
        if(c===b1||c===0&&as===true){
        c = n;
        as=false;
        }
            if(c!=b1){
            b2 = c;
            a1 = false;
            a2 = true;
        }
    }
};
bnc();
console.log("new1");
console.log(b1,b2,b3,b4,b5);
//_______________________________________
var bnc2 = function(){
    var n = Math.floor(Math.random() * 5+1)+0;
    var n2 = Math.floor(Math.random() * 5+1)+0;
    var a1 = true;
    var as = false;
    while(a1){
        var c = n;
        if(c===b1||c===b2||c===0&&as===false){
        c = n2;
        as=true;
        }
        if(c===b1||c===b2||c===0&&as===true){
        c = n;
        as=false;
        }
        if(c!=b1&&c!=b2){
            b3 = c;
            console.log("made it 1");
            a1 = false;
        }
    }
};
bnc2();
console.log("new2");
console.log(b1,b2,b3,b4,b5);

最佳答案

once it actually hits a number that's the same

它永远不应该。这样的算法take longer the longer they run .你应该采取不同的方法:

将所有可能的数字放入一个池中。抽取一个数字后,将其从池中删除。就像在现实生活中所做的那样。

var pool = [1, 2, 3, 4, 5];
var getNumber = function () {
    if (pool.length == 0) {
        throw "No numbers left";
    }
    var index = Math.floor(pool.length * Math.random());
    var drawn = pool.splice(index, 1);
    return drawn[0];
};

关于javascript - 唯一随机数生成器 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584716/

相关文章:

python - 有没有办法懒惰地解压无限生成器?

javascript - HTML 中的随机图像背景

java - 用元素随机填充网格的最快方法

javascript - NodeJS初学者: Fetching data from other URL using Requestify

javascript - app.get 和 app.post 在 node.js 中获取值

linux - Windows 下 Keys 的随机数生成器 - 从 Linux 移植

generator - 如何在mern.io中生成新模块?

python - Python 中生成器的使用

javascript - 导航栏表现奇怪

javascript - 直接在 render 函数中使用 React.forwardRef