[Shell] Random number

Source: Internet
Author: User
Tags rand uuid



Random number between 0-1
# awk ' Begin{srand ();p rintf "%.16f\n", Rand ()} '

Random number between 0-20
# awk ' Begin{srand (); Sum=rand () *21;printf ("%d\n", Sum)} '
# echo ' Expr $RANDOM% 21 '
# echo ' Expr $ (expr $ (date +%n)% 20) + 1 '
# echo ' Expr $ (date +%n)% 21 '
# echo ' Expr $ (date +%s%n)% 21 '

Random 10 numbers and sort
Ascending
# for I in ' seq 1 ';d o echo $RANDOM;d One | Sort-n
Descending
# for I in ' seq 1 ';d o echo $RANDOM;d One | Sort-nr



First, get random numbers by time (date)
This is what we often use, we can say that time is unique, and will not repeat, from this inside to obtain the same time unique value. Adapted to all the programs inside.
Example:


[[email protected] shell] $ date +% s
1287764773
#Get timestamp, currently until: 1970-01-01 00:00:00 seconds apart
#If you use it for random numbers, the data for the same second is the same. When doing loop processing, the multi-threading basically cannot meet the requirements.
 
[[email protected] shell] $ date +% N
738710457
#Get nanosecond data for the current time, accurate to one hundredth of a second.
#This is quite accurate. Even in multiple CPUs and a large number of loops, the same result is difficult to appear in the same second, but there will be a lot of repeated collisions at different times.
 
[[email protected] shell] $ date +% s% N
1287764807051101270
#This can be said to be perfect, adding a timestamp and adding nanoseconds


Using it to make a base of random numbers, let's see how to get a random number in a piece of data.


#! / bin / sh
#Write a random function, call the method random min max
#Get random integers directly at min and max
#copyright chengmo QQ: 8292669
#Get the random number return value, update the value after calculating the random number in the shell function
function random ()
{
     min = $ 1;
     max = $ 2- $ 1;
     num = $ (date +% s +% N);
     ((retnum = num% max + min));
     #Perform the remainder operation
     echo $ retnum;
     #Here, print out the value by echo, and then get the value of the function, stdout can get the value
     #There is a return, define the full price variable, and then the function changes the content and reads outside
}
 
#Get 1-10 seq data items
for i in {1..10};
do
     out = $ (random 2 10000);
     echo $ i, "2-10000", $ out;
done;


Within a loop, the resulting values are different.
This is our common method, adapt to a variety of languages, is a general algorithm, even if the server does not provide, at some point the same unique data marker, we can also use this method to do their own pseudo-random number. Here's an easier way to do it, don't let us do it ourselves.

2. Through internal system variables ($RANDOM)
In fact, Linux has provided a system environment variables, is directly random number, haha, think just learning method, is not in vain!!


 
[[email protected] shell]$ echo $RANDOM
10918
[[email protected] shell]$ echo $RANDOM
10001
#连续2次访问, the result is not the same, this data is an integer less than or equal to 5 bits


It may be doubtful if the number of random numbers more than 5 bits is available.
Oh, add a fixed 10-bit integer, and then to seek redundancy, as in Example 1. The next example is our self-reliance.
3. Generate random Numbers (/dev/random,urandom) by unique data within the system
We know the dev directory below, is Linux some of the default devices, it gives us the feeling is to put the keyboard, hard disk, CD-ROM and other devices of the corresponding files. In fact, some Linux equipment is very special, has a special purpose. We said earlier:/dev/[udp|tcp]/host/port is more special. Oh, it's far away.
A/dev/random device that stores real-time data about the environment in which the system is currently running. It can be thought of as the system's unique value data at some point, so it can be used as a random-number meta-data. We can read the data in the file read mode. /dev/urandom This device data is the same as in random. Only, it is a non-blocking random number generator, and the read operation does not cause blocking.
Instance:


[[email protected] shell] $ head -1 / dev / urandom
ãÅ † ù ... • KTþçanVÕã¹Û & ¡ õ¾ "ô2íùU"? F¦_ ÿ "† mEðûUráÏ = J¯TŸA • ÌAÚRtÓ
 
#Read a line, why is it garbled? In fact, it saves real-time data through binary data, so how do we turn it into integer data?
 
 
[[email protected] ~ / shell] $ head -200 / dev / urandom | cksum
1615228479 50333
#Since urandom's data is very large, it cannot be read directly by cat. Here, the first 200 rows are taken. In fact, the entire data is changed, and how much is taken is unique.
#cksum will read the content of the file and generate the unique integer data. As long as the content of the file is unchanged, the generated result will not change. With the php crc function
 
[[email protected] shell] $ head -200 / dev / urandom | cksum | cut -f1 -d ""
484750180
#cut with "" split, then get the first field data of the split

The

Gets the integer data, and then a method like one can get to the random number. Digression: In the program, we often MD5 get unique values, and then the string, if you want to represent an integer mode, you can pass the CRC function. CRC is cyclic redundancy check, the same data through the operation, will get a string of integer data. This validation is now widely used. For more information, refer to: CRC.
There is another way to read the generated UUID code directly from the device.
4, read the Linux UUID code
before mentioning this, there is a concept, what is the UUID? The full name of the
UUID code is a universal unique identifier (universally unique Identifier, UUID), which is a standard for software construction and also for the Free Software Foundation (Open Software Foundation, OSF) A part of the organization in the field of distributed computing environments (distributed Computing Environment, DCE). The purpose of the
UUID is to allow all elements in a distributed system to have unique identifying information, without the need to specify the identifying information through the central control side. In this way, everyone can create a UUID that does not conflict with others. In such a case, there is no need to consider the name duplication problem when the database was created. It makes the UUID code generated by any computer on the network, which is the only one on the Internet throughout the server network. Its original information will be added hardware, time, machine current operation information and so on. The
UUID format is: Contains 32 16 digits, with a "-" connection number is divided into five paragraphs, in the form of 8-4-4-4-12 32 characters. 550e8400-e29b-41d4-a716-446655440000, so: The total number of UUID in theory is 216 x 8=2128, approximately equal to 3.4 x 1038. That is, if you produce 1 trillion uuid per second, it will take 10 billion years to run out of all the UUID.
In fact, we do database design time, must have heard, GUID (Global unique identifier) code, it is actually similar to the UUID, supported by Microsoft. This code is basically generated by the operating system kernel. It's easy to get this UUID code in Windows, whether it's a database or any other software, you remember.
The UUID code for Linux
Linux has a kernel-provided UUID code, which is/proc/sys/kernel/random/uuid in this file. In fact, the random directory, there are many other files, are related to the generation of UUID.


[[email protected] ~ / shell] $ cat / proc / sys / kernel / random / uuid
dff68213-b700-4947-87b1-d9e640334196
[[email protected] ~ / shell] $ cat / proc / sys / kernel / random / uuid
7b57209a-d285-4fd0-88b4-9d3162d2e1bc
#Read 2 times in a row, the uuid obtained is different
 
[[email protected] ~ / shell] $ cat / proc / sys / kernel / random / uuid | cksum | cut -f1 -d ""
2141807556
#Same method as above to get random integers 


[Shell] Random number


Related Article

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.