Yemi Oyepeju
Yemi Oyepeju

Reputation: 3

jQuery random count with no number repeat until end of loop

I've been trying hard at this. A jQuery counter function that counts from 0 to 6 continuously in random but no repeat of a number until end of the loop i.e. until the count of the 7th digit in the array. Currently the following code works for me but the numbers repeat. Please help!

function beginTimer() {
    if ($('#timer').html().length == 0) {
        timer(0) ;  
    }
}

function timer(i) {
    setTimeout("timer(" + (i) + ")", 1000);
    $('#timer').html(Math.floor(Math.random() * 6));
}

Upvotes: 0

Views: 2389

Answers (3)

Old Pro
Old Pro

Reputation: 25547

You need to create an array of the 7 digits, randomize the array by shuffling the deck (do not use sort, despite what fearless leader says), output them, then start again. There's no way to avoid repeats without maintaining the list of numbers already output.

JS Fiddle

var digits = [0, 1, 2, 3, 4, 5, 6];
digits.shuffle = function () {
    var i = this.length,
        j, temp;
    while (--i >= 0) {
        j = Math.floor(Math.random() * (i + 1));
        temp = this[i];
        this[i] = this[j];
        this[j] = temp;
    }
    this.lastOutput = -1;
};
digits.shuffle();

var output = function () {
    var i = ++digits.lastOutput;
    if (i >= digits.length) {
        digits.shuffle();
        i = 0;
    }

    $('#timer').html(digits[i]);
    this.lastOutput = i;
    setTimeout(output, 1000);
};

output();

Upvotes: 1

adeneo
adeneo

Reputation: 318182

var counted = [];

function count() {
    var numb, go = true;

    while (go) {
        numb = Math.floor(Math.random() * 6);
        if (counted.indexOf(numb) == -1) counted.push(numb), go = false;
    }

    $('#timer').html(numb);
    if (counted.length > 5) counted = [];
    setTimeout(count, 300);
}

FIDDLE

Upvotes: 0

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

You can create an array of "digits" and pick from them until it no longer exists.

var digits = [];

// populate our digits array with 0-6
for(var i = 0; i < 6; i++)
    digits.push(i);

function timer() {
    // are there still digits remaining?
    if(!digits.length)
        return;

    // select a random digit and remove it from the array
    var digit = digits.splice( Math.floor( Math.random() * digits.length ), 1 );

    $('#timer').html(digit);

    setTimeout(timer, 1000);
}

JSFiddle

Upvotes: 0

Related Questions