数学随机数不重复以前的数字 [英] math random number without repeating a previous number
问题描述
似乎无法找到答案,说我有这个:
Can't seem to find an answer to this, say I have this:
setInterval(function() {
m = Math.floor(Math.random()*7);
$('.foo:nth-of-type('+m+')').fadeIn(300);
}, 300);
我如何做到让随机数不会重复.比如随机数是2,我不想2再出来.
How do I make it so that random number doesn't repeat itself. For example if the random number is 2, I don't want 2 to come out again.
推荐答案
有多种方法可以实现这一点.
There are a number of ways you could achieve this.
解决方案A:如果数字的范围不大(比方说小于 10),您可以只跟踪您已经生成的数字.然后,如果您生成重复项,则将其丢弃并生成另一个数字.
Solution A: If the range of numbers isn't large (let's say less than 10), you could just keep track of the numbers you've already generated. Then if you generate a duplicate, discard it and generate another number.
方案B:预先生成随机数,将它们存储到一个数组中,然后遍历该数组.您可以通过取数字 1,2,...,n
然后将它们打乱来完成此操作.
Solution B:
Pre-generate the random numbers, store them into an array and then go through the array. You could accomplish this by taking the numbers 1,2,...,n
and then shuffle them.
shuffle = function(o) {
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;
};
var randorder = shuffle([0,1,2,3,4,5,6]);
var index = 0;
setInterval(function() {
$('.foo:nth-of-type('+(randorder[index++])+')').fadeIn(300);
}, 300);
解决方案 C:跟踪数组中可用的数字.随机选择一个数字.从所述数组中删除数字.
Solution C: Keep track of the numbers available in an array. Randomly pick a number. Remove number from said array.
var randnums = [0,1,2,3,4,5,6];
setInterval(function() {
var m = Math.floor(Math.random()*randnums.length);
$('.foo:nth-of-type('+(randnums[m])+')').fadeIn(300);
randnums = randnums.splice(m,1);
}, 300);
这篇关于数学随机数不重复以前的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!