0

I have to generate 3 random numbers from 0-9 every 2 seconds, it works however there will be instances where i get duplicate values for example 4 7 7 . It would be great is someone could point out my mistake, thanks

if (firstNum == secondNum || firstNum == thirdNum) {
  firstNum = Math.floor((Math.random() * 9) + 1);
} else if (secondNum == firstNum || secondNum == thirdNum) {
  secondNum = Math.floor((Math.random() * 9) + 1);
} else if (thirdNum == firstNum || thirdNum == secondNum) {
  thirdNum = Math.floor((Math.random() * 9) + 1);
}
Ele
  • 33,468
  • 7
  • 37
  • 75
  • 5
    Does this answer your question? [Generate unique random numbers between 1 and 100](https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100) – AZ_ Feb 03 '20 at 14:35

3 Answers3

1

Keep it simple

setInterval(function(){
  let first_number  = parseInt(Math.random()*10),
    second_number = null,
    third_number  = null;

  while (second_number == third_number || first_number == second_number || third_number == second_number){
    second_number = parseInt(Math.random()*10);
    third_number = parseInt(Math.random()*10);
  }

  console.log(first_number, second_number, third_number)
},2000)
besciualex
  • 1,872
  • 1
  • 15
  • 20
0

You need to remove those "else". If firstNum is equal to the secondNum or the thirdNum it won't verify if the others are equal to each other or not, because it stopped on the first if.

Try this:

if (firstNum == secondNum || firstNum == thirdNum) {
  firstNum = Math.floor((Math.random() * 9) + 1);
} 
if (secondNum == firstNum || secondNum == thirdNum) {
  secondNum = Math.floor((Math.random() * 9) + 1);
} 
if (thirdNum == firstNum || thirdNum == secondNum) {
  thirdNum = Math.floor((Math.random() * 9) + 1);
}
0

If statements work when you look for just 3 numbers, but that would be a nightmare to handle if you were looking for more numbers. Consider this solution:

const uniqueNumbers = [];

while (uniqueNumbers.length < 3) {
 const number = Math.floor((Math.random() * 9) + 1);
  
  if (!uniqueNumbers.includes(number)) {
   uniqueNumbers.push(number)
  }
}

console.log(uniqueNumbers)

Please note that the code above is a simple example that does not validate the range. You might trap yourself in an infinite loop if you do not watch out (say, you want 20 unique numbers in a range from 1-10).

Nightray
  • 93
  • 3