4 replies [Last post]
gautamz07
gautamz07's picture
Offline
Enthusiast
Last seen: 5 years 10 weeks ago
Timezone: GMT+5.5
Joined: 2014-04-24
Posts: 265
Points: 403

Why has the author of the quiz written the function like this . Look below

 function getRandomInt(min, max) {
     return Math.floor(Math.random() * (max - min)) + min;
 }
 
var temp = getRandomInt(0,3);
alert(temp);

The part that confuses me is why has he added "+min" at the end , what possibly does he want to achieve ?

Thanks .

gautam

Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 5 weeks 5 days ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

Hi gautamz07, Math.random()

Hi gautamz07,
Math.random() returns a number greater then or equal to 0 and less then 1.
0 times anything is 0, so adding min to the end just ensures you have a number at least equal to min.

gautamz07
gautamz07's picture
Offline
Enthusiast
Last seen: 5 years 10 weeks ago
Timezone: GMT+5.5
Joined: 2014-04-24
Posts: 265
Points: 403

Thanks

Thank you tony , But i still don't get why the + min at the end ?

gary.turner
gary.turner's picture
Offline
Moderator
Dallas
Last seen: 39 weeks 1 day ago
Dallas
Timezone: GMT-6
Joined: 2004-06-25
Posts: 9776
Points: 3858

max - min defines the range.

max - min defines the range. Multiply by the result of math.random() and you need to then add the min value.

Step by step for a min value of 4 and max value of 7

random() -> value of 0 =< x < 1, for example, 0.6

times the range 3 -> 1.8

1.8 + min = 5.8 which is => 4 and < 7

cheers,

gary

If your web page is as clever as you can make it, it's probably too clever for you to debug or maintain.

gautamz07
gautamz07's picture
Offline
Enthusiast
Last seen: 5 years 10 weeks ago
Timezone: GMT+5.5
Joined: 2014-04-24
Posts: 265
Points: 403

Thanks gary

Thanks for your elaborate explanation @gary