Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 218
Damovisa Avatar asked Feb 11 '10 15:02

Damovisa


People also ask

What is a 7 digit code?

In seven-digit dialing, only the central office code and the station number is dialed, indicating that the call destination is within the local area code. This was the standard in most of North America from the 1950s onward.

How many unique 7 digit numbers are there?

Hence, answer is 90,00,000.


2 Answers

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;
}
like image 124
kennytm Avatar answered Sep 19 '22 20:09

kennytm


You could use an incrementing ID and then XOR it on some fixed key.

const int XORCode = 12345;

private int Encode(int id)
{
    return id^XORCode;
}

private int Decode(int code)
{
    return code^XORCode;
}
like image 24
Robin Day Avatar answered Sep 17 '22 20:09

Robin Day