How can I create a unique 7-digit code for an entity?

Damovisa picture Damovisa · Feb 11, 2010 · Viewed 7.7k times · Source

When a user adds a new item in my system, I want to produce a unique non-incrementing pseudo-random 7-digit code for that item. The number of items created will only number in the thousands (<10,000).

Because it needs to be unique and no two items will have the same information, I could use a hash, but it needs to be a code they can share with other people - hence the 7 digits.

My original thought was just to loop the generation of a random number, check that it wasn't already used, and if it was, rinse and repeat. I think this is a reasonable if distasteful solution given the low likelihood of collisions.

Responses to this question suggest generating a list of all unused numbers and shuffling them. I could probably keep a list like this in a database, but we're talking 10,000,000 entries for something relatively infrequent.

Does anyone have a better way?

Answer

kennytm picture kennytm · Feb 11, 2010

Pick a 7-digit prime number A, and a big prime number B, and

int nth_unique_7_digit_code(int n) {
    return (n * B) % A;
}

The count of all unique codes generated by this will be A.

If you want to be more "secure", do pow(some_prime_number, n) % A, i.e.

static int current_code = B;
int get_next_unique_code() {
   current_code = (B * current_code) % A;
   return current_code;
}