0

I feel like this should be an easy exercise:

1.- Generate 10 random numbers (0-99) and storage in an array.

2.- Numbers should not repeat.

But all the answer I get from the internet are very complicated or excessive long code.

In the code below I already generate the 10 numbers, but they keep repeating. Any ideas?? (i tried If/else but it didn't work) :(

numbers=[]
for(i=0;i<10;i++){
var oneRandomNum = Math.floor(Math.random()*100);
numbers.push(oneRandomNum); 
}

console.log(numbers);

Thank you so much!!!!! :)

Pnfyorch
  • 35
  • 5
  • Code works fine on my browser, no repeat after 10 numbers, as per your want. Conversations around random number generators talk alot about repetition in regards to creating the things like the Math.random() function which is actually a pseudo random number generator which repeats its sequence once every gazillion iterations because its very good but none the less still repeats itself (but beyond the scope of your question) The code works fine. Try "copy snippet to answer" from CertainPerformance and cut paste your own code. It works fine. – Stephen Duffy Apr 12 '20 at 05:09
  • 1
    @StephenDuffy The chance of randomly selecting 10 numbers in the range [0 to 99] and finding they are all different numbers is about 63%, making the probability of getting at least one repeated number about 37%. If you add code to check for duplicates in the numbers array produced, you should be able find some , but it will probably (in it's techical sense) take several attempts. – traktor Apr 12 '20 at 05:31

1 Answers1

2

You can repeatedly add numbers to a Set, and stop when its size reaches 10:

const set = new Set();
while (set.size !== 10) {
  set.add(Math.floor(Math.random() * 100));
}
const numbers = [...set];
console.log(numbers);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you for your answer. It works perfect. I never seen [...set] or set.size before. I was trying to use forEach or filter, I'm very new at Javascript. Thank you!!! :) – Pnfyorch Apr 12 '20 at 05:28