Some invitation codes and activation codes are usually generated on the WEB. It must be unique and random. Below we will summarize some common methods for generating random codes and share one of our methods:
1. Write the code by yourself to generate a random combination of numbers and letters. Each generated random number goes to the database to check whether the random code already exists. if it already exists, it is generated again until it is not repeated.
Advantage: no advantages are found.
Disadvantage: the generation speed is slow, and the database needs to be queried. When the data volume is large, the chance of duplication may be high. You need to query the database multiple times.
2. guid. This method should be used more often.
Advantage: easy to use, no additional code needs to be written.
Disadvantage: it occupies a relatively large amount of database space, especially the query speed based on guid (after all, it is a string ).
3. When the primary key + random code is used, the random code we generate will certainly have a primary key when saved to the database. It can be combined with this primary key + random character. Generation steps:
1) first obtain the id from the id generator, such as 155.
2) Fill in a string with a fixed number of digits (for example, 8 digits) (enter 0 on the left of the number that is not enough, and use this number directly if the number exceeds the number). The value is 00000155.
3) insert a random letter or other non-digit symbol behind each number to obtain: 0A0F0R0Y0H1K5L5M
In this way, we can get a random and unique invitation code.
Advantage: it is easy to use and does not need to query the database. The biggest advantage is that you can directly obtain the primary key id based on the invitation code During query,
Then, query the database based on the id (FAST), and compare whether the queried invitation code is consistent with the invitation code submitted by the user.
Disadvantage: You need to use the id generator. If the primary key is auto-incrementing by the database, it is not easy to use (you need to insert the database to obtain the id and then update the invitation code ).
4. Sometimes the product manager says that I require numbers for the invitation codes. Why? No why? I like it. * (& ^ (^ % & ^ $ Use method 3 to implement unique random numbers.
1) Get id: 155
2) convert to octal: 233
3) convert to a string and add the '9' character to it: 2339
4) A number of random numbers are generated at the end: 2003967524987
After it is converted to the octal format, the character '9' is not displayed, and then a '9' is added to the end to determine the uniqueness. Finally, you can generate random numbers.
Advantages and disadvantages
At present, Methods 3 and 4 are used in our products. I feel that it is okay.
PS: The above is my personal opinion. If you have a better method, please share it with me. Pai_^