en.javascript.info/1-js/4-data-structures/2-number/8-random-min-max/solution.md
2016-03-06 00:59:16 +03:00

503 B

We need to "map" all values from the interval 0..1 into values from min to max.

That can be done in two stages:

  1. If we multiply a random number from 0..1 by max-min, then it the interval of possible values increases 0..1 to 0..max-min.
  2. Now if we add min, the possible interval becomes from min to max.

The function:

function random(min, max) {
  return min + Math.random() * (max - min);
}

alert( random(1, 5) ); 
alert( random(1, 5) ); 
alert( random(1, 5) );