1

I have the following code (see below) in a HTML file that generates random numbers between the range 100000-999999 (It works fine) but I want to make sure it does not REPEAT itself. How do I modify it or add code to do that?

       
 
var randomnumber = Math.floor(Math.random()*999999) + 100000
document.write(randomnumber)
       
Graham Jansen
  • 25
  • 1
  • 7

1 Answers1

3

You can keep track of all numbers that are already used:

var numbers = [];
var randomnumber;
do {
    randomnumber= Math.floor(Math.random()*999999) + 100000;
} while (numbers.includes(randomnumber));
numbers.push(randomnumber);     
document.write(randomnumber)

If ES6 is a problem (array.prototype.includes), you can use array.prototype.indexOf :

// ...
do {
    randomnumber= Math.floor(Math.random()*999999) + 100000;
} while (numbers.indexOf(randomnumber) !== -1);
// ...
Faly
  • 13,291
  • 2
  • 19
  • 37