Home > Enterprise >  How can we Generate Unique Number in android/Kotlin?
How can we Generate Unique Number in android/Kotlin?

Time:04-19

I was working on a project where we needed to generate a unique number for the Firebase Realtime Database. Now I want to generate a random 8- to 12-digit number that will be unique. Can anyone provide a suitable method/algorithm for obtaining the number, or can it be combined with string?

CodePudding user response:

If you truly need a random number with NN digits you should use Kotlin's Random:

 val random = abs((0..999999999999).random()) 

Of course, in this, 0 is a valid number in this sequence. So what do you do in in the 111 billion chances you get 0? well, that's up to you. You could change the range (but less numbers = less randomness)

You could "pad" 0s to your number so 123 becomes 000000000123 (as a String, that is). Ultimately what you do with the random number is up 2 you.

Keep in mind Random also takes a Seed.

So you could become more fancy by using the time at UTC as the seed (which is constantly changing every instant):

val random = abs(Random(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)).nextLong())

This will likely give you HUGE numbers so you should convert to string and take the last NN digits

If you get for eg.:

2272054910131780911

You can take: 910131780911

I have created a simple playground where you can see this in action. Please understand I made this in 10 minutes, so there may be optimizations all over the place, I don't have the Kotlin standard library in my head and the Playground's autocomplete is not the same as Android Studio.

CodePudding user response:

You can use Current Milli Second as Unique Number as follows

/**
 * @param digit is to define how many Unique digit you wnat
 * Such as 8,9,10 etc
 * But digit must be Min 8 Max 10
 * Int  is 32 bits  max size -2,147,483,648 to 2,147,483,647
 */
fun getUID(digit:Int):Int{
    var currentMilliSeconds:String = "" Calendar.getInstance().timeInMillis
    var genDigit:Int = digit
    if(genDigit<8)
        genDigit = 8

    if(genDigit>10)
        genDigit = 10

    var cut = currentMilliSeconds.length - genDigit
    currentMilliSeconds = currentMilliSeconds.substring(cut);
    return currentMilliSeconds.toInt()
}

Call it like

var UID = getUID(10)//parameter value can be 8-10 

CodePudding user response:

Possibly look into SecureRandom -- Cryptographically strong random number generator (RNG): https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html

Also, see this post regarding how long of a random number to generate by using SecureRandom: How to generate a SecureRandom string of length n in Java?

  • Related