roflol roflol - 3 months ago 7
Javascript Question

JavaScript - random multiple of 20 between 0 - 580

In Javascript, how do I create a random even number multiplied by 20 between 0 - 580?

E.g.: 220, 360, 180, 0 (min), 400, 200, 580 (max)

Answer

You want increments of 20, so what you really need is an integer in the range 0 to 29, and then multiply with 20. Example:

var max = (580/20) + 1;
var result = 20 * (Math.floor(Math.random())*max)

We are adding one to max, because Math.random() is a uniformly distributed number between (inclusive 0) and (exclusive 1), so since we use Math.floor, the maximum must be 1 larger.

Comments