How to make random number generator not generate t

2019-08-29 04:41发布

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

Thanks a lot to any help!

3条回答
forever°为你锁心
2楼-- · 2019-08-29 05:03

This can be accomplished by shuffling the array first, as explained in an earlier answer.

kfy(array);
for (var i = 0; i < 4; ++i) {
    $('#' + array[i]).addClass('bomb');
}
查看更多
看我几分像从前
3楼-- · 2019-08-29 05:11

this is example of your topic problem ( from 1 to 13 )

for (var i = 0, ar = []; i < 14; i++) { ar[i] = i; }
console.log( ar.sort(function () { return Math.random() - 0.5; }) );

output:

[1, 2, 0, 3, 5, 6, 13, 4, 8, 9, 12, 10, 7, 11] ->> run first time
[3, 7, 4, 10, 1, 9, 11, 8, 13, 12, 2, 5, 0, 6] ->> runt second time
etc..
查看更多
女痞
4楼-- · 2019-08-29 05:26

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

Hope this helps!

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

查看更多
登录 后发表回答