Generate Unique ID from Alphanumeric String
Asked Answered
G

2

10

I need to generate a UNIQUE id (int only) from an Alphanumeric string.

e.g. I have security id = 'ABC123DEF' I should be able to generate an unique ID (int only) of "security id" so that the unique ID is always constant.

e.g. Security ID : ABC123DEF Int ID : 9463456892

So that I can store the Int ID in Database and refer the security ID from Int ID anytime.

Some Examples: PBG_CD_20120214_.2 | 201202-CMG188963_T | PBG_TD_20120306_.0001 3 examples :-PIPE seperated

Gap answered 24/9, 2012 at 19:11 Comment(2)
You're very specific it must be an int, but please define int? The number you put is too large for a traditional int which refers to 32-bits usually, though fits in a long. What are the space contraints of the numeric ID?Select
Hi Jimmy Its can be Long int. May be i should put in this way. The generated ID should be in "Numberic (0 - 9)"Gap
P
34

Just use the Java hashing algorithm. Not 100% unique but you can use it as a base and add something to guarantee uniqueness on a much smaller collision set:

public static int hash(String s) {
    int h = 0;
    for (int i = 0; i < s.length(); i++) {
        h = 31 * h + s.charAt(i);
    }
    return h;
}

In order to avoid collision 100%, you need a prime number that is bigger than the wider difference between your characters. So for 7-bit ASCII, you need something higher than 128. So instead of 31, use 131 (the next prime number after 128). The part I haven't checked is if the generated hash will wind up being bigger than the size of your long ints. But you can take it from there...

Pontus answered 24/9, 2012 at 19:24 Comment(2)
Don't forget to approve the answer for the benefit of the community if it worksPontus
Elegant solution! Ported it in maxscript (3dsmax scripting), tested it and so far i didn't have any collision. This is gem!Caligula
A
2

You could encode each character as a two-digit number, 0-9 as the numbers themselves, 10-35 as A-Z.

For example, 9AC8 would be 09 10 12 08 = 09101208.

EDIT: For a small number you could use this approach (with Java-style pseudocode):

char[] availableChars = ['A', 'B', ... , '0', ... '9', '-', '_', '.'];
long hash = 0;
long base = 1;
for (char c in string.toCharArray())
    for (int key=0; key < availableChars.length; key++)
        if (availableChars[key] != c)
            continue;
        hash += base*key;
        base = base*availableChars.length

return hash;
Abernathy answered 24/9, 2012 at 19:15 Comment(4)
I have an Alphanumeric String : Like "201202-CMG277440_T"Gap
Is there a limit to how large your numbers can be?Abernathy
No - No Limit on how large the number can be.Gap
Then if you had two additional numbers for the hyphen and underscore, this algorithm will work. If you need smaller numbers, I have a suggested solution as wellAbernathy

© 2022 - 2024 — McMap. All rights reserved.