math random number without repeating a previous number

Viewed 46866

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.

10 Answers

Use sets. They were introduced to the specification in ES6. A set is a data structure that represents a collection of unique values, so it cannot include any duplicate values. I needed 6 random, non-repeatable numbers ranging from 1-49. I started with creating a longer set with around 30 digits (if the values repeat the set will have less elements), converted the set to array and then sliced it's first 6 elements. Easy peasy. Set.length is by default undefined and it's useless that's why it's easier to convert it to an array if you need specific length.

let randomSet = new Set();
for (let index = 0; index < 30; index++) {
        randomSet.add(Math.floor(Math.random() * 49) + 1) 
    };
let randomSetToArray = Array.from(randomSet).slice(0,6);
console.log(randomSet);
console.log(randomSetToArray);

An easy way to generate a list of different numbers, no matter the size or number:

     function randomNumber(max) {
          return Math.floor(Math.random() * max + 1);
        }
        
        const list = []
        while(list.length < 10 ){
            let nbr = randomNumber(500)
            if(!list.find(el => el === nbr)) list.push(nbr) 
        }
        
        console.log("list",list)

Related