-1

I have this function which gives me a random number between min and max, excluding the numbers in notthis. How do I change it to give me a number that is an even number.

function getrandomnumber(min,max,notthis)
{
  var num=min+Math.floor((max-min+1)*Math.random());
  var j=notthis.indexOf(num)

  while (j!=-1)
  {
     num=min+Math.floor((max-min+1)*Math.random());
     j=notthis.indexOf(num)
  }
  return num;
}

a=getrandomnumber(0,100,"0,10,20")
document.write(a)
Agu V
  • 2,091
  • 4
  • 25
  • 40
Mike
  • 67
  • 2
  • 8
  • One approach could be to generate a number between `min` and half-way to `max`, then just multiply that number by 2. – David May 06 '16 at 17:12

3 Answers3

2

Will this work for you? You should use mod operator to identify even no. it will be cleaner I think..

function generateRandom(min, max, myArray) {
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    return (myArray.includes(num) || num%2 != 0) ? generateRandom(min, max,myArray) : num;    
}

myArray = [2, 7, 13, 14, 15];
var test = generateRandom(1, 1000, myArray);
Jomet-abc
  • 45
  • 8
0

If i understand the question correctly, you could divide the number by 2 and if it is not zero, then is even.

function getrandomnumber(min,max,notthis)
{
  var num=min+Math.floor((max-min+1)*Math.random());
  var j=notthis.indexOf(num)

  if (j!=-1 && num % 2 == 0)
  {
    return num;
  }else{
    getrandomnumber(min,max,notthis);
}

a=getrandomnumber(0,100,"0,10,20")
document.write(a)
Agu V
  • 2,091
  • 4
  • 25
  • 40
0

For posterity, inspired by my answer for Java.

function randomIntFromInterval(min, max) { // min and max included 
    return Math.floor(Math.random() * (max - min + 1) + min);
}

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
function randomEvenIntFromInterval(min, max) {
    if (min % 2 != 0) ++min;
    return min + 2 * randomIntFromInterval(0, (max-min)/2);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
function randomOddIntFromInterval(min, max) {
    if (min % 2 == 0) ++min;
    return min + 2 * randomIntFromInterval(0, (max-min)/2);
}

Slightly inefficient, but very readable.

rouble
  • 16,364
  • 16
  • 107
  • 102