Generate a random value in a track, excluding a track

4

Using Javascript how to do a range with random values with a deleted internal range?

Exemplifying:

  

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

     

| | = accepted value | x | = value denied

Code used:

function gen(min, max, excludeMin, excludeMax){
  var value;
  while(value > excludeMin && value < excludeMax){
    value = Math.random() * (max - min) + min;
  }
  return value;
}
    
asked by anonymous 16.01.2015 / 13:41

1 answer

3

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

meuLog(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;
}

function meuLog(msg) {
  div = document.body;
  div.innerHTML = div.innerHTML + '<p>' + msg + '</p>';
}

I thought of setting an initial value that met the condition, but this case is complicated, not always possible.

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

//seria bom verificar se recebeu null antes de usar o valor
meuLog(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;
}

function meuLog(msg) {
  div = document.body;
  div.innerHTML = div.innerHTML + '<p>' + msg + '</p>';
}

It does not have to be exactly this logic, you give the treatment you want, but if the value that should be smaller is greater than what should be larger, loop exits immediately after the first number. It may even be what you want but it stays alert.

    
16.01.2015 / 13:57