none
Generate a Unique alphanumeric from given numbers RRS feed

  • Question

  • Hi,

    I want to generate a ticket number from the combination:

    Member ID (which is the primary key from my database starting from 1)

    A Timestamp

    How can I generate a 6 digits unque alphanumeric from this?

    Thanks,

    Jassim

    Wednesday, May 16, 2018 1:13 PM

All replies

  • If you only have 6 digit entropy, the only possible way is to store the ticket number in table, and for each ticket number generated later, you check the table to see if the number was already created first, then either add 1 or use the algorithm to generate another number (because afterall, you mentioned timestamp would be a part of the algothm. Generating again should give different number), rinse and repeat until the number generated is not used.

    Now for the algorithm itself, something like concatenating the strings then call .GetHashCode() and return the first or last 6 digits will do.


    Thursday, May 17, 2018 2:01 AM
    Answerer
  • what about 12 digits? is it the same way or there is a better way to do it?
    Thursday, May 17, 2018 7:55 AM
  • There is no 6 character unique key. Standard is the Global Unique Key. (Guid in .Net known by that name)

    https://msdn.microsoft.com/en-us/library/system.guid.newguid(v=vs.110).aspx

    There is no way go keep it in line with a number, because then it would be senseless. 

    Probably you have a autonumber primary key, that can be replaced by a GUID.


    Success
    Cor

    Thursday, May 17, 2018 9:12 AM
  • but i want a shorter digits, let's say starting from 6

    then what's the best way to have a unique ticket number? even if numbers only

    Thursday, May 17, 2018 9:14 AM
  • Since GetHashCode() returns 32-bit value, will return at most 10 digit numbers. So you'll want to use other algorithm for better effect.

    Guid.NewGuid() suggested by Cor Ligthert is good, alternatively you can use functions like MD5.ComputeHash() or else. As long as you use table to guard against collision, what algorithm you choose is up to you.

    Thursday, May 17, 2018 9:53 AM
    Answerer
  • Usually generating a ticket means adding a new row to Tickets table, therefore you can use the auto-generated ID as a Ticket Number (maybe transforming the ID; for example: get a hexadecimal representation, shuffle the digits, etc.).

    Check the next attempt too:

    UInt32 member_id = 123456;
    
    UInt32 timestamp = unchecked((UInt32)( DateTime.Now - new DateTime( 2018, 1, 1 ) ).TotalSeconds);
    
    UInt64 t = ( (UInt64)member_id << 32 ) | timestamp;
    
    string ticket = "";
    
    UInt32 b = 'Z' - 'A' + 1 + 10;
    
    do
    {
        UInt64 r = t % b;
        t = t / b;
        ticket = (char)( r < 10 ? '0' + r : 'A' + r - 10 ) + ticket;
    } while( t != 0 );
    
    ticket = ticket.PadLeft( 11, '0' );
    
    Console.WriteLine( ticket );
    


    Thursday, May 17, 2018 10:16 AM