Search code examples
vb.netrandomlogicunique

Approach to generate unique short number for current day


I need to generate a number that is unique for the current day, I'm bound to use short data type and I tought to use hour/minute to achieve that. This is my VB code:

Dim ora As String = dataora.Substring(6, 2) 'es. 07
Dim minuti As String = dataora.Substring(8, 2) 'es 14
Dim parteOra = ora * 1000
Dim parteMinuti = rando.Next(0, 708)
Dim parteFinale = rando.Next(0, 9000)
Dim CUL as short = CShort(parteOra + (minuti + parteMinuti) + parteFinale)

Knowing that short data type manage a 0-32767 range (from 0 up, I can't use negative) my question is: with the code above can I be 100% sure that in the same day I will always have an unique number?

My logic is:

  • hour in 24h format is unique 0-23 number
  • minutes is unique 0-59 number in the same hour
  • parteOra can go from 0 to 23000
  • minuti + parteMinuti can go from 0 to 767
  • parteFinale can go from 0 to 9000
  • putting all togheter I should have a range from 0 to 32767

Solution

  • If you have to use signed small int as your data type, and can only use non negative values (values in the range of 0-32,767) - as Andrew Morton suggested, you can create unique values per 1 day by multiplying the current minute since midnight by 20 and then add an increasing counter from 0 to 19. The counter's value resets to 0 at the beginning of every minute, every minute.
    The max value would be for the 19th employee checking in at 11:59pm - 28,799 which is inside the desired range.
    Note that if more than 20 employees check in within the same minute, this system would fail.

    Example:
    For employees checking in at 4:37pm - the possible values within that minute would be 19,940-19,959 (4:37pm = 997 minutes since midnight, multiply by 20: 997*20=19,940.

    If you are able to use unsigned small int as your data type (this type uses 2 bytes per value, just like the signed small int data type), then the values can range from 0-65,535. In this case, you can even allow 45 employees to check in within the same minute: multiply the current minute since midnight by 45 and then add an increasing counter from 0 to 44. The counter's value resets to 0 at the beginning of every minute, every minute.

    Example:
    For employees checking in at 11:03pm - possible values within that minute would be 62,235-62,279.