12-31-2016, 09:21 PM
(This post was last modified: 01-03-2017, 11:52 AM by Aphatheology.)

Here I want to show you a tip for creating a random number between 1 and N in easiest and shortest way.

Code

Here is the code:

~~(Math.random () * N ) + 1

Code in textarea:

All you need to do is to replace N with your upper number.

How?

In JavaScript we have Math.random () which creates a random number between 0 and 1, e.g. 0.3577353348955512.

We use this function to have a random number, then we multiply that to our upper number (e.g. 6):

0.3577353348955512 * 6 =

2.1464120093733072

And then we get the floor number with double ~ operator

Code

Here is the code:

~~(Math.random () * N ) + 1

Code in textarea:

All you need to do is to replace N with your upper number.

How?

In JavaScript we have Math.random () which creates a random number between 0 and 1, e.g. 0.3577353348955512.

We use this function to have a random number, then we multiply that to our upper number (e.g. 6):

0.3577353348955512 * 6 =

2.1464120093733072

And then we get the floor number with double ~ operator

It takes so long to learn simplicity.