0

a question from a beginner. So I've used

let myArray = [];

function randomNumbers(){
  for(let i = 0; i < 3; i++){
    if(Math.floor(Math.random()*10) !== myArray[i]){
      myArray.push(Math.floor(Math.random()*10));
    }
  }
}

randomNumbers()
console.log(myArray)

Code above gives me 3 random number as intended but sometimes it's giving me same number twice and in very rare occasion, same number 3 times.

lejlun
  • 4,140
  • 2
  • 15
  • 31
  • You can create your array with numbers 0 to 9, then shuffle that array, and grab the first 3 numbers from that array – Nick Parsons Aug 14 '21 at 07:49

2 Answers2

2

When generating random numbers, there is always the chance of getting duplicates. However as you specifically require 3 random numbers, I'd suggest checking that each number you generate does not already exist in the array of numbers.

I can see you have somewhat attempted to ensure that the same number isn't added twice in a row, however as you call Math.random() twice, once in the if and once when you push the number, you will actually be generating a new number each time.

Try instead using .includes() to check if the number already exists in the array.

Something like this:

let myArray = [];

function randomNumbers() {
  for (let i = 0; i < 3; i++) {
    while (!myArray[i]) {
      let newRandomInt = Math.floor(Math.random() * 10);
      if (!myArray.includes(newRandomInt)) {
        myArray.push(newRandomInt)
      }
    }
  }
}

randomNumbers()
console.log(myArray)
Tom Gionfriddo
  • 410
  • 2
  • 8
  • Thank you very much for your quick response! Will have a check at .includes() :) –  Aug 14 '21 at 07:45
  • 1
    I wouldn't bother with the for...loop. Just have `while` check `myArray.length`. – Andy Aug 14 '21 at 08:00
  • 1
    @Andy tried and it works! Thanks for the help guys, I always had this idea that for loop is just always better than while or do while loop but I guess not –  Aug 14 '21 at 08:04
  • 1
    @Andy good point, thanks I'll update my solution – Tom Gionfriddo Aug 14 '21 at 08:11
0

here is array generate numbers without repeatition demo

Aab B
  • 75
  • 6
  • Thanks for your response, the code you've shown me seems nice but it's gonna take me some time to understand. Have a good day! –  Aug 14 '21 at 07:45
  • 3
    @AabB - Welcome to Stack Overflow, when answering questions it's often good to explain your answer to be of most benefit to the OP and future readers (code comments that you've added are good though). Stack Overflow also allows you to embed runnable snippets into your answer, without having to take readers off-site to view parts of your answer. Here is how you can make one: [I've been told to create a "runnable" example with "Stack Snippets", how do I do that?](https://meta.stackoverflow.com/q/358992) – Nick Parsons Aug 14 '21 at 07:53
  • Okay but it has no library – Aab B Aug 14 '21 at 08:18