本文介绍了独特的随机数生成器Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个有趣的宾果游戏.我在很多地方寻找了一个独特的生成器,但似乎找不到一个.我已经尝试过制作自己的游戏,但是一旦它实际上命中了一个相同的数字,就会执行无限循环.我尝试了一个简单的代码,该代码理论上应该可以工作,但是由于某些原因,事情还是会通过.我该怎么办!?

I'm trying to make a bingo game for fun. I've looked in a lot of places for a unique generator but I can't seem to find one. I've tried to make my own,but once it actually hits a number that's the same it does an infinite loop. I've tried a simple code that in theory should work but for some reason things pass through. What can I do!?

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

推荐答案

它永远都不会.这样的算法运行时间越长,花费的时间就越长.您应该采用其他方法:

It never should. Such algorithms take longer the longer they run. You should take a different approach:

将所有可能的数字放入池中.绘制数字后,将其从池中删除.就像在现实生活中一样.

Put all possible numbers into a pool. Once you draw a number, remove it from the pool. Just like it's done in real life.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 17:50
查看更多