Monday, 18 August 2014

How to randomly generate -1 or +1, in one line.

A hobby of mine is avoiding if statements, with mathematical formula that return the right number based on other conditions.

It is easy to generate a 0 or a 1 randomly, simply use Math.round(Math.random());

That will work in a number of languages, or something similar.

For a random -1 or +1, try this:

var randNum = -1 + (2*Math.round(Math.random));

If the random number generated by Math.random() is 0.5 or above, then the answer will be 1. If the random number generated is less than 0.5, the answer will be 1.

Enjoy!

No comments:

Post a Comment

Please enter your message here...