In daily life, random numbers are often encountered, such as wanting to throw dice, draw lots, and draw lots. Haha, it can be achieved very simply. So when doing programming, it is really not easy to design random numbers by yourself. Nowadays, many operating system kernels will provide corresponding APIs. These original parameters are to obtain the original information of some computer running, such as memory, voltage, physical signals, etc., and their value can be guaranteed to be unique in a time period. OK, I won’t say nonsense. hehe.
What methods do we have to obtain random numbers?
1. Get a random number through time (date)
This is also what we often use. It can be said that time is unique and will not be repeated. Get the unique value of the same time from this. Adapt to all programs.
example:
[chengmo@centos5 shell]$ date +%s
1287764773
#Get the timestamp, currently to: 1970-01-01 00:00:00 Number of seconds apart
#If you use it as a random number, the data for the same second is the same. When doing loop processing, the requirements cannot be met in multithreading.
[chengmo@centos5 shell]$ date +%N
738710457
#Get nanosecond data for the current time, accurate to one billionth of a second.
#This is quite accurate. Even in multiple CPUs, a large number of loops, it is difficult to have the same result in the same second, but there will be a large number of repeated collisions at different times.
[chengmo@centos5 shell]$ date +%s%N
1287764807051101270
#This can be said to be quite perfect, with a timestamp added and a nanosecond added
Through the above explanation, we use it to be the cardinality of random numbers. Next, let’s see how to obtain random numbers in a piece of data.
#!/bin/sh
#Write a random function and call the method random min max
#Get random integers directly in min and max
#copyright chengmo QQ:8292669
#Get the return value of the random number, calculate the random number in the shell function, update the value
function random()
{
min=$1;
max=$2-$1;
num=$(date +%s+%N);
((retnum=num%max+min));
#Just perform the remainder calculation
echo $retnum;
# Here, print out the value through echo, and then get the function's value, stdout can be obtained
#There is another type of return, defines the full price variable, and then modify the content of the function and read it outside.
}
#Get 1-10 seq data items
for i in {1..10};
do
out=$(random 2 10000);
echo $i,"2-10000",$out;
done;
Check out the running results:
[chengmo@centos5 shell]$ sh
1,2-10000,5600
2,2-10000,5295
3,2-10000,3432
4,2-10000,3148
5,2-10000,9041
6,2-10000,4290
7,2-10000,2380
8,2-10000,9009
9,2-10000,5474
10,2-10000,3664
In a loop, the values are different.
This is our common method, adapted to various languages, and is a general algorithm. Even if the server does not provide it, we can also use this method to make our own pseudo-random numbers. There is a simpler way below, don’t do it ourselves.
2. Pass internal system variable ($RANDOM)
In fact, Linux already provides a system environment variable, which is directly a random number. Haha, I think it's in vain to learn the method just now! !
[chengmo@centos5 shell]$ echo $RANDOM
10918
[chengmo@centos5 shell]$ echo $RANDOM
10001
#2 consecutive visits, the results are different. This data is an integer less than or equal to 5 digits.
Maybe there is a question, how can I get a random number with more than 5 digits?
Haha, add a fixed 10-bit integer and then calculate the remaining number, the same as in Example 1. The next example is when we are self-reliant.
3. Generate random numbers (/dev/random, urandom) through unique data within the system
We know that under the dev directory are some default devices for Linux, which gives us the feeling that they are the corresponding files of keyboards, hard disks, optical drives and other devices. In fact, some Linux devices are very special and have special uses. What we mentioned earlier: /dev/[udp|tcp]/host/port is quite special. Haha, it's a long way to go.
/dev/random device stores real-time data of the current environment in which the system is running. It can be regarded as the system at some point, unique value data, and therefore can be used as random number metadata. We can read the data inside through file reading. The data of the /dev/urandom device is the same as in random. It's just that it's a non-blocking random number generator, and the read operation will not block.
Example:
[chengmo@centos5 shell]$ head -1 /dev/urandom
ãņù…•KTþçanVÕã¹Û&¡õ¾“ô2íùU“ žF¦_ ÿ”†mEðûUráÏ=J¯TŸA•ÌAÚRtÓ
#When reading 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?
[chengmo@centos5 ~/shell]$ head -200 /dev/urandom | cksum
1615228479 50333
#Because there is a lot of data in urandom, it cannot be read directly through cat. Here we take the first 200 rows. In fact, the entire data is changed, and the number of times it takes is the same.
#cksum will read the file content and generate unique integer data. Only if the file content remains unchanged, the generated result will not change, and the php crc function
[chengmo@centos5 shell]$ head -200 /dev/urandom | cksum | cut -f1 -d" "
484750180
#cut splits with "" and then gets the split first field data
Get the integer data, and then, a method similar to one can obtain the random number. Less topic: In the program, we often get a unique value in md5, and then a string. If we want to represent it as an integer, we can pass the crc function.crc is a cyclic redundancy check. When the same data is calculated, we will get a string of integer data. This kind of verification is now widely used. For more information, please refer to:crc.
There is another method below, which directly reads the generated uuid code from the device.
4. Read the uuid code of Linux
Before mentioning this, there is a concept, which is what is uuid?
The full name of the UUID code is a Universally Unique Identifier (UUID), which is a software construction standard and is also part of the organization of the Open Software Foundation (OSF) in the field of distributed computing environment (DCE).
The purpose of UUID is to enable all elements in the distributed system to have unique identification information without specifying identification information through the central control end. This way, everyone can create a UUID that does not conflict with others. In this case, there is no need to consider the duplication of names when the database is created. It will make the uuid code generated by any computer on the network unique to the entire Internet server network. Its original information will be added to the hardware, time, machine current operation information, etc.
The UUID format is: contains 32 hexadecimal numbers, divided into five segments with the "-" connection number, and the form is 32 characters of 8-4-4-4-12. Example; 550e8400-e29b-41d4-a716-446655440000 , so: the theoretical total number of UUID is 216 x 8=2128, which is approximately equal to 3.4 x 1038. In other words, if 1 trillion UUID is generated per second, it will take 10 billion years to use up all UUIDs.
In fact, when you are doing database design, you must have heard that the guid (global unique identifier) code is actually similar to uuid and is supported by Microsoft. The code here is basically generated by the operating system kernel. Remember to make it easy to get this uuid encoding in Windows, whether it is database or other software.
uuid code for Linux
Linux's uuid code is also provided by the kernel, in the /proc/sys/kernel/random/uuid file. In fact, there are many other files in the random directory, all of which are related to the generation of uuid.
[chengmo@centos5 ~/shell]$ cat /proc/sys/kernel/random/uuid
dff68213-b700-4947-87b1-d9e640334196
[chengmo@centos5 ~/shell]$ cat /proc/sys/kernel/random/uuid
7b57209a-d285-4fd0-88b4-9d3162d2e1bc
#Read 2 times in a row, the resulting uuid is different
[chengmo@centos5 ~/shell]$ cat /proc/sys/kernel/random/uuid| cksum | cut -f1 -d" "
2141807556
#Same as above method to get random integers
These are the common active random number integer methods below Linux. Except for the first one, the pseudo-data sources that produce random codes are related to the /dev/random device. It's just that they each appear different. If you have more other methods, please send me a message and share it with you.