数学随机数,不重复前一个数字

编程入门 行业动态 更新时间:2024-10-21 16:04:37
本文介绍了数学随机数,不重复前一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

数学随机数,不重复前一个数字

本文发布于:2023-11-30 20:54:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   数学   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!