jeudi 23 juillet 2020

Losing the logic! Random unique numbers in javaScript

I needed to write a function that'd generate 6 random numbers between 0 and 60 and then store them in a given array. In addition, this function could not store duplicates in the returned array. Well, I found a very helpful answer here on StackOverflow(Thanks Shouvik) which I'm gonna attach bellow. But here's the thing guys I had most of this logic but missed two core elements

1 - I was trying to do this without a second temporary Array 2 - I had no clue how'd I find duplicates inside the arrey

I knew I had to .indexOF the array I knew I had to .push a new value to the array

Here is the code I had prior to finding the solution:

    function gerarDezenas(){
  let jogo = [];
  for (var i = 0;i < 6;i++){
    jogo.push(Math.round(Math.random()*(1 , 60)+1));
    if (jogo.indexOf(jogo) == //clueless){
   .push() // ?? clueless either
    }
  }
return jogo
}
console.log(gerarDezenas())

So I found that I needed another Array and the if condition to compare it to

    function gerarDezenas(){
  let jogo = [];
  for (var i = 0;i < 6;i++){
    var temp = Math.round(Math.random()*(1 , 60)+1);
    if (jogo.indexOf(temp) == -1){
    jogo.push(temp)
    }
    else {
      i--;
    }
  }
return jogo
}

The code is now working as it was intended to but I don't really understand it and that the issue here! I don't know what these lines are doing:

if (jogo.indexOf(temp) == -1){
    jogo.push(temp)
    }
    else {
      i--;
    }
  }

Can somebody clarify to me what the if and the else are doing? If you read through the post thank you very much!

attached image please don't hate me




Aucun commentaire:

Enregistrer un commentaire