数学随机数,不重复前一个数字 [英] math random number without repeating a previous number

查看:165
本文介绍了数学随机数,不重复前一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎无法找到答案,说我有这个:

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屋!

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