1

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);
Devmix
  • 1,599
  • 5
  • 36
  • 73

1 Answers1

2

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.

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.

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:

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);
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • @progx there are plenty of [duplicate questions](https://stackoverflow.com/q/196017/1541563) 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 '18 at 02:37