How to generate random numbers without including a set number? [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to generate random numbers without including a set number? [duplicate]



This question already has an answer here:



I'm just trying to generate 8 random numbers from 1 to 25. My issue is that I already have a variable and its value is 14, with that being said my question is how to generate random numbers from 1 to 25 and if one them is equal to 14 then replace it with another random number? at the end, I want to have 8 random numbers in my array and I don't want to include 14 in it. Can anyone tell me what I'm missing or how to make this more accurate? and sometimes I only end up with 7 elements in my array, does anyone knows why?



Here's my code:




var arr = ;
var currentvar = 14;
for(var i = 0 ; i < 9; i++)
var num = Math.floor(Math.random()*25) + 1;
if(num === currentvar)
num = Math.floor(Math.random()*25) + 1;
else
arr.push(num);



console.log(arr);



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





And you don't care you may have other duplicate values?
– Kaiido
Aug 12 at 2:30





@Kaiido yes I don't want duplicate numbers in my array
– progx
Aug 12 at 2:33




1 Answer
1



Study the logic you've implemented more closely. You go through the loop exactly 9 times (not 8), and you have mutually exclusive outcomes for each iteration due to an if...else control flow.


if...else



Either you reassign num if it's equal to currentvar (which you should do correctly by removing var from the second assignment), or you add it to the array, never both in one iteration. That's what else means, and you probably want a do...while loop to assign num until it is not equal to currentvar.


num


currentvar


var


else


do...while


num


currentvar




var arr = ;
var currentvar = 14;
var num;

for (var i = 0; i < 8; i++)
do
num = Math.floor(Math.random() * 25) + 1;
while (num === currentvar);

arr.push(num);


console.log(arr);



Alternatively, if you want to keep your if...else statement, you can decrement the loop counter i instead to repeat the loop an extra time when num === currentvar:


if...else


i


num === currentvar




var arr = ;
var currentvar = 14;

for (var i = 0; i < 8; i++)
var num = Math.floor(Math.random() * 25) + 1;

if (num === currentvar)
i--;
else
arr.push(num);



console.log(arr);





@progx there are plenty of duplicate questions regarding generating unique random values in a given range of numbers. I would like to point out that this is not what you originally asked.
– Patrick Roberts
Aug 12 at 2:37


Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered