如何使随机数生成器不会两次生成相同的数字 [英] How to make random number generator not generate the same number twice

查看:47
本文介绍了如何使随机数生成器不会两次生成相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程还很陌生,我一直在从事一个项目,该项目会找到四个随机 div 并为它们添加一个类——我唯一的问题是因为我的随机生成器经常生成相同的数字,程序通常不会将类附加到四个随机 div,但很可能是三个甚至两个.所以我的问题是,如果可能的话,我如何将我的程序设置为仅生成四个不同的数字.我听说过 Fisher Yates 的尝试,但我没有完全理解.这是我的 JS:

I'm fairly new to programming and I've been working on a project that finds four random divs and adds a class to them -- my only problem is that because my random generator has been generating the same number frequently, the program usually does not append the class to FOUR random divs but most likely three or even two. So my question is, how, if possible would I set my program to only generate four DIFFERENT numbers. I've heard of the Fisher Yates attempt, but I did not get it fully. Here is my JS:

for(var i = 4; i>0; i--){
var rand = Math.floor((Math.random()*16)+1);
var array=new Array(); 
array[1] = "one";
array[2] = "two";
array[3] = "three";
array[4] = "four";
array[5] = "five";
array[6] = "six";
array[7] = "seven";
array[8] = "eight";
array[9] = "nine";
array[10] = "ten";
array[11] = "eleven";
array[12] = "twelve";
array[13] = "thirteen";
array[14] = "fourteen";
array[15] = "fifteen";
array[16] = "sixteen";
$('#'+array[rand]).addClass('bomb');
}

非常感谢您的帮助!

推荐答案

几点意见: 首先,你应该在 for 循环之外初始化你的数组,这样它只执行一次.此外,正如@zerkms 所指出的,您应该从索引 0 开始数组,而不是从 1 开始.为了防止重复一个数字,您可以简单地从数组中删除您已经选择的那些.以下是如何执行此操作的示例:

A couple of comments: First of all, you should initialize you array outside of the for loop, so that it only does it once. Also, as @zerkms pointed out, you should start your array at index 0, not 1. To prevent repeating a number, you could simply remove the ones you have already chosen from the array. Here is an example of how you could do this:

var array=new Array(); 
array[0] = "one";
array[1] = "two";
array[2] = "three";
array[3] = "four";
array[4] = "five";
array[5] = "six";
array[6] = "seven";
array[7] = "eight";
array[8] = "nine";
array[9] = "ten";
array[10] = "eleven";
array[11] = "twelve";
array[12] = "thirteen";
array[13] = "fourteen";
array[14] = "fifteen";
array[15] = "sixteen";
for(var i = 4; i>0; i--){
    var rand = Math.floor((Math.random()*array.length));
    $('#'+array[rand]).addClass('bomb');
    array.splice(rand,1);
}

希望这会有所帮助!

我删除了导致错误的不必要的 while 循环.

I've removed the unnecessary while loop that caused an error.

这篇关于如何使随机数生成器不会两次生成相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆