25 Apr 2013

Random number in JavaScript

Have you ever to use a random number in your application? Of course it depends on the application or program you are in to. Recently I was  working on a mobile application in which i had to rate the movies between 1 to 5 . Since the backend data was not ready i had to use static code in development phase. So the question was how to rate movies,  In other words  i had to assign a random number between 1 to 5 to a movie.

Lets first try Math.random()
Math.random() returns the a floating point number between 0 and 1. It could return anything like 0.9876567876 or 0.4232457568.
It would not work since i need real number between 1 to 5.


Variant of Math.random()
                           Math.random() * (max - min) + min
This would return a floating point random number between min (inclusive) and max (exclusive).
To rate 1 to 5 , i have to use 1 as a min  to 6 as a max. Not 5 as a max because it is exclusive
                    r =   Math.random() * (6 - 1) + 1
r can be 2.2.711616653897717 or 4.5043663586648925

Yes I want something like this , which would return a random number between two given numbers.
But the problem is it is returning a floating number.
Note that r is real.float. where real part would be always be a random number between min and max.
My problem would be solved if i could get only real part out of it.


Will Math.floor(x) help ?
It would returns the nearest largest integer of x.

So if i pass x as 2.2.711616653897717 i can get 2 (real part).
   e.g.   2 = Math.floor(2.2.711616653897717)


No, I need both random() and floor().
Step 1: get floating point random number
               float_random = Math.random() * (6-1) + 1
Step 2: round off floating number to get real integer
              integer_random = Math.floor(float_random)

integer_random would always be between 1 and 5.

Now i can use this integer_random number to rate the movies. Next time you looking for random number in JavaScript , you know the steps.

No comments:

Post a Comment