Generate a random value in a range, excluding a range

Asked

Viewed 136 times

5

Using Javascript how to make an interval with random values with an internal interval deleted?

Exemplifying:

min | | | | |x|x|x|x|x|x| | | | | max

| | = accepted value |x| = denied value

Code used:

function gen(min, max, excludeMin, excludeMax){
  var value;
  while(value > excludeMin && value < excludeMax){
    value = Math.random() * (max - min) + min;
  }
  return value;
}

1 answer

3


The problem is that the code doesn’t even enter the loop since the initial value does not meet the condition placed. You have to perform the first time unconditionally using do ... while.

console.log(gen(1, 100, 10, 20));

function gen(min, max, excludeMin, excludeMax){
  var value;
  do {
    value = Math.random() * (max - min) + min;
  } while(value > excludeMin && value < excludeMax)
  return value;
}

I put in the Github for future reference.

I thought about set an initial value that met the condition, but this case is complicated, it will not always be possible.

There is still a problem if the parameters are sent inconsistently. Then it would be better to do a check:

//seria bom verificar se recebeu null antes de usar o valor
console.log(gen(1, 100, 10, 20));

function gen(min, max, excludeMin, excludeMax){
  if (min > max || excludeMin > excludeMax) {
    return null;
  }
  var value;
  do {
    value = Math.random() * (max - min) + min;
  } while(value > excludeMin && value < excludeMax)
  return value;
}

I put in the Github for future reference.

It doesn’t have to be exactly this logic, you give the treatment you want, but if the value that should be lower is greater than what should be higher, the loop leaves immediately after the first number. It may even be what you want but gets the alert.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.