math random non repeat same number

Solutions on MaxInterview for math random non repeat same number by the best coders in the world

showing results for - "math random non repeat same number"
Hanae
20 Jan 2019
1let haveIt = [];
2
3function generateUniqueRandom(maxNr) {
4    //Generate random number
5    let random = (Math.random() * maxNr).toFixed();
6
7    //Coerce to number by boxing
8    random = Number(random);
9
10    if(!haveIt.includes(random)) {
11        haveIt.push(random);
12        return random;
13    } else {
14        if(haveIt.length < maxNr) {
15          //Recursively generate number
16         return  generateUniqueRandom(maxNr);
17        } else {
18          console.log('No more numbers available.')
19          return false;
20        }
21    }
22}
23
24
25console.log(generateUniqueRandom(10));
26console.log(generateUniqueRandom(10));
27console.log(generateUniqueRandom(10));
28console.log(generateUniqueRandom(10));
29console.log(generateUniqueRandom(10));
30
31console.log(generateUniqueRandom(10));
32
33
34console.log(generateUniqueRandom(10));
35console.log(generateUniqueRandom(10));
36console.log(generateUniqueRandom(10));
37console.log(generateUniqueRandom(10));
38console.log(generateUniqueRandom(10));
39console.log(generateUniqueRandom(10));
40console.log(generateUniqueRandom(10));
41
42
43console.log('Unique random numbers:' ,haveIt);
44
45