Showing posts with label random. Show all posts
Showing posts with label random. Show all posts

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!

Monday, 3 October 2011

How to Shuffle an Array in One Line

I often have to get a randomised version of an array, and I used to do it like this:

Create an empty array for the shuffled version
(Within a for loop) {
Get a random index using Math.floor(Math.random() * array.length)
Put the value from the unordered array into the ordered array, using the random index
Remove the value from the unordered array, again using the random index.
}

But now:

(Within a for loop) {
array.push(array.splice(Math.floor(Math.random() * array.length),1));
}

One line, no need for an empty array to be created.