简体   繁体   中英

Random number generation except some given numbers

I'm searching for a primary key for CMS that I'm creating that not be in an ascending or descending sequence so I decided to use random numbers.

I want to use random numbers as PK and because of possibility of repetitive numbers;Is possible to giving an array of numbers that shouldn't be in next random generation ?

I'm not using any database.

You could try Guid :

string guid = Guid.NewGuid().ToString("N");

From msdn:

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated

An interesting link that is against counting and pro guids.

I have to say that I would recommend leveraging a text file if you're not using a database. In the text file would be a single value -the counter -and the code would look like this:

lock (_lockObj)
{
    var cntr = Convert.ToInt32(File.ReadAllText("path to counter file"));
    var newKey = cntr;
    cntr++
    File.WriteAllText("path to counter file", cntr.ToString());
}

where _lockObj is declared like this at the class scope:

private readonly object _lockObj = new Object();

One note here is that the class you get the counter from needs to be a Singleton because you don't want to have more than one _lockObj .


On another note, if you are going to share this amongst users you will want to make this class accessible via a service that all of them share (eg web service) so that when you lock the file they are all locking against the same lock object and thus waiting for each other.

Whether you're using a database (which I would strongly recommend), or a text-file, or something else, there is the problem of checking new keys against used keys; this will not be a problem at first, since you will have few used keys to begin with. If you add a lot of numbers though, validating a new key will take more time, as there will be more keys to compare to.

You could solve this by generating all the keys once, to begin with, and delete used keys (or mark them as used) each time a key is used.

Without getting to specific about the details: You could for instance generate 500'000 rows (or more) in a table, and include a row-number, a PK, and a field marking a row as "used". When you need a new key, select the PK from a random row, and mark that row as used (or delete it, if you prefer).

If you use a text-file, you could do the same, making sure to delete each "picked" line as you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM