Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to generate a random string (8 digit alphanumeric code) and save it with my Tournament row into a database.

Problem is that this code needs to be unique in the whole table and random (not incremental) because I don't want it to be predictable (people using it to join tournament).

So I need something to genreate a code but when it already is in table then generate new one. One way is to generate code, then check database existance, then generate new in case of conflict. But this solution have many problems like it can run forever and its is slow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
112 views
Welcome To Ask or Share your Answers For Others

1 Answer

The answer is to use a unique identifier that combines a "unique" part and a "random" part.

  • The "unique" part can be a monotonically increasing counter (such as the record or row number in a database), or it can be a number generated with a full-period linear congruential generator (which cycles pseudorandomly through all possible values in its period before repeating).
  • The "random" part is simply a random number generated with a cryptographic random number generator (which Node.js has; check the documentation). In general, the longer it is, the less predictable it will be.

Moreover, for the purposes of generating unique identifiers, there is little reason to limit yourself to 8-character alphanumeric identifiers as you're now doing.

Even if you expect end users to enter a "random" and "unique" ID at some point, there are techniques you can use to ease the task of entering IDs much longer than 8 characters; they include—

  • adding a "checksum" character to the ID,
  • dividing the ID into hyphen-separated chunks, and
  • employing a system similar to Bitcoin's BIP39, in which each ID is convertible to a sequence of memorable words.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...