Szymon
Szymon

Reputation: 1290

count random without duplicate

I'm looking for random counting without duplicate numbers I found something like this without comment random

        var randnums = [0,1,2,3,4,5,6];

        setInterval(function() {
            var m = Math.floor(Math.random()*randnums.length);
            $('ul li:nth-of-type('+(randnums[m])+')').animate({
                opacity:1
            },400)
            console.log(randnums[m])
        }, 300);

EXAMPLE: CODEPEN

What I want to accomplish:

I was looking for help all over net for long time with no positive result.

Upvotes: 0

Views: 139

Answers (2)

Teemu
Teemu

Reputation: 23396

Test this:

var randnums = [0, 1, 2, 3, 4, 5, 6],
    delay = setInterval(function () {
        var m = Math.floor(Math.random() * randnums.length);
        console.log(randnums[m]);
        randnums.splice(m,1);
        if (!randnums.length) {
            clearInterval(delay);
        }
    }, 300);

splice() is a very important part of this script, it "throws away" a used number. I've also added a check, which stops the interval, when all numbers are used.


EDIT

You can create an array of length of X with a for loop, for example:

var randnums = [], n, len = 12;
for (n = 0; n < len; n++) {
   randnums.push(n);
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

An alternative to splicing, if you want to be able to reuse the array or loop the animation, try this:

var randnums = [0,1,2,3,4,5,6];
randnums.sort(function(a,b) {return Math.random()-0.5;}); // "shuffle" the array
setInterval(function() {
    var n;
    randnums.push(n = randnums.shift()); // cycle the first element to the back
    // do something with n
},300);

Upvotes: 0

Related Questions