Generating a random number within the specified range is a common operation
- First understand Math.random () function, which returns a default value is 0 or more but less than 1 [0,1)
- If you want to generate a random number between 0 ~ X (not including X), just to Math.random () returns the value multiplied by X, then the range is [0, X)
- Think about it, in fact, step by step on the ride can be seen as random range zoom function, so in fact is multiplied by (X - 0), which is the upper bound minus the lower bound
- In the previous step to know if you want to get a random number range, first need to enlarge the range of the random function, to be obtained if [a, b] the random number in the range required
- Zoom range, Math.random () * (ba) But here there was a problem
- When a number is 0, the function returns [0, b) between, the results do not include b
- When a is not 0, the function returns a number between [0, BA), B is not included in the results, this case needs to be changed Maht.random () * (ba) + a, range becomes [a, B)
- If the limit increase, only an integer, the floor function may be used, known Math.random () X-return [0, X), then Math.random () X-return. 1 + [0, x + 1), then the next rounding the lower bound plus Math.floor (Math.random () * (max - min + 1) + min) can be obtained integer [min, max] of
- If without this restriction, the function currently no direct method, can be solved by rounding the lower portion only exceeds max
- Zoom range, Math.random () * (ba) But here there was a problem
- If you want to generate a random number between 0 ~ X (not including X), just to Math.random () returns the value multiplied by X, then the range is [0, X)