Examples of math.random () random numbers in JavaScript

Source: Internet
Author: User
Tags current time modulus


Definitions and usage

The random () method can return a random number between 0 ~ 1.

Grammar

Math.random ()

return value

A pseudo random number between 0.0 ~ 1.0.

Open node, enter terminal command line mode, enter Math.random ():


>math.random ()

0.436846193857491
The result is not as usual. A pseudo random number less than 1 jumps out. This time, if people ask you, what other options can generate random numbers, you will think of God Horse.
Time passes quickly, around.
If you continue to enter new Date ()-0 in the terminal:
1
2
3
>newdate ()-0

1404488829907
I think you can get an increase in numbers, yes, is "seconds", if you say that the goods where the random, please do not worry:
Javascript


> (newdate ()-0)%10086

8657
Here the modulus of the number can be greater than 2 and preferably less than the current time value, you can get the modulus of the probability of one of the random number of probabilities.
If the number of your modulo is random, then two of the visible variables that produce this random number are random, is it approximate to the true "random number"?
Of course, if you use this trick, you also need to take into account the hardware and language execution process time, because we know that the computer execution, there is a time of precision of the category, so a little delay to use the suppression.
Pull some useless, you may be in a hurry, then please remain curious, we continue to say a little boring things.
Math.random will provide us with a random number between [0,1], but if we want [1,10] range of random integers, you can use the following three functions:
Math.Round
Math.ceil
Math.floor\
Let's start by generating a random number:


>math.random () * (10-1) +1

8.26644050120376\
And then we're going to use these three math builtin functions:


>math.round (8.26644050120376)

8

>math.ceil (8.26644050120376)

9

>math.floor (8.26644050120376)

8
When you change the value to 8.56644050120376, look at it again:


>math.round (8.56644050120376)

9

>math.ceil (8.56644050120376)

9

>math.floor (8.56644050120376)


So the difference at a glance, for floating-point numbers, round will comply with rounding rules, ceil anyway greedy carry +1,floor in any case carefully from the broken arm-1, as for the whole number, I try it.
Speaking of which, the following is a normal description:
Q: How to quickly generate a random piece of text, such as a captcha or a random number token we visit the site.
The answer is a lot, I say a classic, in fact, the idea is very simple, just generate random number of methods to choose one randomly. toString ():


Math.random (). toString. substring (7);
Of course, it can be written like this
Javascript
1
Math.random (). toString. Slice (2);
or use time.

(Newdate () -0). ToString (36)

Just output some, we can see the output of the string parameters are not the same length:


MPTZULNB3XR
 
87jx7vkuik9
 
761qsolayvi
 
amqx2mx6r
 
Ce5uyvkuik9
 
5IOUFIM5CDI
 
dirp4hiwwmi
 
Ioe597ldi
 
Ohn9izfr
&NBSP
sprsakk2o6r
 
5G3RUO6FLXR
 
...
&NBSP
//Simple time to do random is not generated miserable
 
//And do not do random delay suppression, repeat too obvious
 
hx7pom3y
 
hx7pom3z
 
Hx7pom40
 
Hx7pom41
 
hx7pom42
 
hx7pom43
 
Hx7pom44
 
Hx7pom45
Let's take a look at why we use ToString () to generate random numbers: The first guy, regardless of whether the random number seeds generated, or the time increment of the long integer, they are all constructed of the number constructor [ Object number], and in Ecma.js, this method of number is this:
JavaScript


/**

@param {Number} [radix]

@return {string}

*/

Number.prototype.tostring=function (radix) {};
As a good man, I'll show you the way, MDN documents
Did you think of the second parameter of the parseint function after you read it? We found that this native function supports 2~36 (if more than 36, then 26 letters are not enough to the pro) conversion, so if the generation of random switching into the system, take the results of the random position, the effect will be better, you can try.
If you want to get the letters a little bit more and average, then only use 36, but no matter how you hide, there is a possibility of a string of numbers.


Xjuk0zxofen1xlxr
Is there a good way to solve this problem, answer:


Math.random (). toString (+). Replace (/[^a-z]+/g, ')


Or so

Math.random (). toString. Slice (2). Replace (/\d/g, ")
This time, you might say, the article is over, this method looks very cool and concise. However, have you ever thought about a problem, in retrospect, the random number can be 0,1,... These integers ...
When the random number is the value, I'm sorry, the return value is the original value, that is, the 0,1,..., we get the final result will be an empty string, and if it is 0.5 this kind of some with 5-terminated floating-point number, the result is still the case. And when the number is some time, the generated random number of digits will be relatively short ...
To solve this problem, you can of course regenerate this random number, until it outputs a random number of your content to let him go, but we just learned that the way to generate a large random number is to rely on time, elementary school or junior high school, with a relatively small number divided by a relatively large number, The result is a smaller floating-point number to solve the problem.


(Math.random ()/+newdate ()). toString. Replace (/\d/g, "). Slice (1)

In this way, we get a relatively long and fair number of random numbers. You can use node to verify that:


Varc={},r;for (vari=0,j=10000000;i<j;i++) {r= (Math.random ()/+newdate ()). ToString (+). Replace (/\d/g, ""). Slice ( 1); c[r]?c[r]+=1:c[r]=1;} for (Variinc) {if (c[i]===1) {deletec[i];}} Console.log (c);

The run result is no conflict, of course this may be a small probability event. If you think you're on the back, you can try the following paragraph and manually perform it several times to see if there is a result that is not an empty array.


for (vari=0,j=100;i<j;i++) {(function () {varc={},r;for (vari=0,j=1000;i<j;i++) {r= (Math.random ()/+newdate ()). toString. Replace (/\d/g, ""). Slice (1); c[r]?c[r]+=1:c[r]=1;} for (Variinc) {if (c[i]===1) {deletec[i];}} Console.log (c);} ())}

Of course, you can also use the code above the two test examples, using the following method, multiple output several random strings, and then pieced together.


for (varc= ';c.length<5;) c+=math.random (). toString (+). substr (2)

You're tired of this trick, let's take a look at the example in the following series, extract characters from a fixed dictionary to form a random string:
Depending on the map method of array, pay attention to compatibility, of course, you from the MDN side copy a hacks can also be seamless, is not looking tall a bit:


Array.apply (0,array (5)). Map (function () {

Return (function (charset) {

Returncharset.charat (Math.floor (Math.random () *charset.length))

} (' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '));

}). Join (');

But maybe it's easier for you to accept this a little bit more:


Functionrand (length,current) {

Current=current?current: ';

Returnlength?rand (--length, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz". CharAt (Math.floor ( Math.random () *60)) +current): current;

}
or more traditional:


Functionrand () {

Vartext= "";

Varpossible= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (vari=0;i<5;i++) Text+=possible.charat (Math.floor (Math.random () *possible.length));

Returntext;

}
Maybe you think this is the end of the game, too young too simple, before playing the number of the original function, we can also do the foot is a string of the original function, such as we know that the letter ASCII is [65,97], then when this interval is a dictionary, If we randomly take this range, does something interesting happen?


Functionrand (x) {

Vars= "";

while (s.length<x&&x>0) {

Varr=math.random ();

S+=string.fromcharcode (Math.floor (R *26) + (r>0.5?97:65));

}

Returns

}
Simply enter a phone number (recommended to enter a shorter number), and then wait and see if the following results will appear:


Jrxknxrhwjzgckokczrpfxmxdbfqbrpaegvpvmtcihihfcxtmxrhtpegdyxzxwmbbqdvebwxprwhqdmcerizlwuyfapnxpxjoxbafeohsaeqvixbijvpfboln Vurhjsvdfwgtfvdselmlwzowvqbjtcwrgcschgvsxclungxtrtnyvvwyfqesstotxnsrqlhaiycxzlxdqtuzsofjaghyxrwxjusjrtpuviyiilojrglknptqh Lbakwgepniwzctfanrhiqlhyngwuyupsdpljfgxbujbouwcdgkskfclknazoupsxfqiynkfcobapybsjkzjpkwefcygywrbofpvormzbrbafowrkxvujloktz Peodsesbexygbmssnadnbwrvjdgunjsmyfgcxifapenolygxbrhrobslaicgldiwvqp
This topic, seems to say a little numb, change a demand for it. Some sites will play some random background color of the small pattern. Is there an elegant solution:
Follow the definition of the random number function to get the numerical value between the color values is good, read the above code, this sentence, very understood cutting:


' # ' + (0x1000000+ (Math.random ()) *0xffffff). ToString (). substr (1,6)

Of course, you can write a more intuitive solution:


With decimal data to replace the 16 data operation, please note that because the right is an open interval, than the above 0xFFFFFF +1, and finally convert the result back to 16, and then trim the string, output

Math.floor (Math.random () *16777216). toString (16);

' #000000 '. Slice (0,-color.length) +color;



Or a shorter look as follows

"#" + ("000000" +math.floor (Math.random () *16777216). toString). substr (-6);
There is another kind of pattern, as follows:


Functionrandomcolor () {

Varr=function () {Returnmath.floor (Math.random () *256)};

Return "RGB (" +r () + "," +r () + "," +r () + ")";

}
The output is as follows:

RGB (29,236,191)

It's late, and finally, let's say random sort arrays.
On the shuffle algorithm, the internet spread a lot, random choice of a simulation on the good, such as casually write the full rearrangement:


 
Vari=0,data=[],r
 
for (; i<10;data[i++]=i),
 
while (i) {
 
  R=math.round (Math.random () *9+1)-1;
 
  data[i]=data[i]+data[r],data[r]=data[i]-data[r],data[i]=data[i]-data[r];
 
}
 
Console.log (data)
or by using the Array.prototype.sort () function, where the values are not brought in to the operation. The
First math.random () produces a value between [0,1], minus it with a fairer value of 0.5, with a probability of less than 0, equal to 0, greater than 3, and Array.prototype.sort () expecting a value that is exactly [ -1,0,1 is not very convenient.
 
Vari=0,data=[],r
 
for (; i<10;data[i++]=i);
 
Data.sort (function () {
&NBSP
  Return.5-math.random ();
 
Time is not early, tomorrow has to get up early, first write here, think of what, add what.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.