-3

I have a requirement to get a random number other than a given number and between the range in java script. for example the given number is 1 i need a random number between 0-4 other than the given number 1

used
Math.floor(Math.random()*5)

to get random number from 1 to 4

but if the given number is 1 it should not return that number from the range 0-4

i expect to get a number ranging from 2 to 4 if i give a number 1 as range is from 0-4

user3349850
  • 225
  • 1
  • 3
  • 21

1 Answers1

0

You can use while loop and generate the random number until its not different than given.Below is the demo

function getRandomNum(num){
  let x = Math.floor(Math.random() * 5);
  while(x === num){
    x = Math.floor(Math.random() * 5)
  }
  return x;
}
document.querySelector('button').onclick = function(){
  document.querySelector('div').innerHTML = getRandomNum(1)
}
<button>Get Random Number</button>
<div></div>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73