math random number without repeating a previous nu

2019-01-04 12:47发布

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

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.

8条回答
爷的心禁止访问
2楼-- · 2019-01-04 13:14

You seem to want a non-repeating random number from 0 to 6, so similar to tskuzzy's answer:

var getRand = (function() {
    var nums = [0,1,2,3,4,5,6];
    var current = [];
    function rand(n) {
        return (Math.random() * n)|0;
    }
    return function() {
      if (!current.length) current = nums.slice();
      return current.splice(rand(current.length), 1);
    }
}());

It will return the numbers 0 to 6 in random order. When each has been drawn once, it will start again.

查看更多
Ridiculous、
3楼-- · 2019-01-04 13:22

Generally my approach is to make an array containing all of the possible values and to:

  1. Pick a random number <= the size of the array
  2. Remove the chosen element from the array
  3. Repeat steps 1-2 until the array is empty

The resulting set of numbers will contain all of your indices without repetition.

Even better, maybe something like this:

var numArray = [0,1,2,3,4,5,6];
numArray.shuffle();

Then just go through the items because shuffle will have randomized them and pop them off one at a time.

查看更多
登录 后发表回答