1

var = randNum;

function getRandomNum(min, max){ return Math.floor(Math.random() * (max- min + 1)+ min)

randNum = getRandomNum(1 , 6);

console.log(randNum);

WhozWho
  • 21
  • 5
  • The accepted answer [here](https://stackoverflow.com/a/1527820/479156) uses the same logic and also explains it. – Ivar Apr 23 '22 at 08:56

1 Answers1

0

Let's breakit down We need to find random number in range (min, max)

Math.random() returns a random number between 0 and 1(excluded) Ex (0.1, 0. 245, ... so on) Since our range starts from min Hence we need to add min to the random number min + Math.random()

But this will allow you random values only from min to min + 1

To make sure that we cover the entire range from min to max, we multiply the difference between those numbers max - min

This is good, but we only need Integer numbers, hence we round it to floor value using Math.floor And to account for that exclude 1 from Math.random() we add it to the value

Hence it becomes Math.floor(Math.random() * (max- min + 1)+ min)

Bishwajit jha
  • 384
  • 3
  • 9