我们如何在 android/Kotlin 中生成唯一编号?
How can we Generate Unique Number in android/Kotlin?
我正在做一个项目,我们需要为 Firebase 实时数据库生成一个唯一编号。现在我想生成一个随机的 8 到 12 位数字,该数字将是唯一的。谁能提供一个合适的 method/algorithm 来获取号码,或者它可以与字符串结合使用吗?
您可以使用当前毫秒作为唯一编号,如下所示
/**
* @param digit is to define how many Unique digit you wnat
* Such as 8, 10, 12 etc
* But digit must be Min 8 Max 12
*/
fun getUID(digit:Int):Long{
var currentMilliSeconds:String = ""+Calendar.getInstance().timeInMillis
var genDigit:Int = digit
if(genDigit<8)
genDigit = 8
if(genDigit>12)
genDigit = 12
var cut = currentMilliSeconds.length - genDigit
currentMilliSeconds = currentMilliSeconds.substring(cut);
return currentMilliSeconds.toLong()
}
这样称呼它
var UID = getUID(12)//parameter value can be 8-12
如果您确实需要一个 NN 位的随机数,您应该使用 Kotlin 的随机数:
val random = abs((0..999999999999).random())
当然,在这其中,0
是这个序列中的有效数字。那么在你得到 0 的 1110 亿次机会中你会做什么呢?好吧,这取决于你。您可以更改范围(但更少的数字 = 更少的随机性)
您可以将 0s
“填充”到您的号码,以便 123
变为 000000000123
(即,作为字符串)。最终你对随机数所做的事情是 2 你。
请记住随机也需要一个种子。
因此,您可以通过使用 UTC 时间作为种子(它每时每刻都在不断变化)变得更加花哨:
val random = abs(Random(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)).nextLong())
这可能会给您带来巨大的数字,因此您应该转换为字符串并取最后 NN 位数字
如果你得到例如:
2272054910131780911
您可以参加:910131780911
I have created a simple playground 您可以在其中查看实际效果。请理解我在 10 分钟内完成了这个,所以可能到处都有优化,我脑子里没有 Kotlin 标准库,而且 Playground 的自动完成功能与 Android Studio 不同。
可能会研究 SecureRandom -- 加密强随机数生成器 (RNG):https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html
另外,请参阅此 post 关于使用 SecureRandom 生成的随机数的长度:
我正在做一个项目,我们需要为 Firebase 实时数据库生成一个唯一编号。现在我想生成一个随机的 8 到 12 位数字,该数字将是唯一的。谁能提供一个合适的 method/algorithm 来获取号码,或者它可以与字符串结合使用吗?
您可以使用当前毫秒作为唯一编号,如下所示
/**
* @param digit is to define how many Unique digit you wnat
* Such as 8, 10, 12 etc
* But digit must be Min 8 Max 12
*/
fun getUID(digit:Int):Long{
var currentMilliSeconds:String = ""+Calendar.getInstance().timeInMillis
var genDigit:Int = digit
if(genDigit<8)
genDigit = 8
if(genDigit>12)
genDigit = 12
var cut = currentMilliSeconds.length - genDigit
currentMilliSeconds = currentMilliSeconds.substring(cut);
return currentMilliSeconds.toLong()
}
这样称呼它
var UID = getUID(12)//parameter value can be 8-12
如果您确实需要一个 NN 位的随机数,您应该使用 Kotlin 的随机数:
val random = abs((0..999999999999).random())
当然,在这其中,0
是这个序列中的有效数字。那么在你得到 0 的 1110 亿次机会中你会做什么呢?好吧,这取决于你。您可以更改范围(但更少的数字 = 更少的随机性)
您可以将 0s
“填充”到您的号码,以便 123
变为 000000000123
(即,作为字符串)。最终你对随机数所做的事情是 2 你。
请记住随机也需要一个种子。
因此,您可以通过使用 UTC 时间作为种子(它每时每刻都在不断变化)变得更加花哨:
val random = abs(Random(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)).nextLong())
这可能会给您带来巨大的数字,因此您应该转换为字符串并取最后 NN 位数字
如果你得到例如:
2272054910131780911
您可以参加:910131780911
I have created a simple playground 您可以在其中查看实际效果。请理解我在 10 分钟内完成了这个,所以可能到处都有优化,我脑子里没有 Kotlin 标准库,而且 Playground 的自动完成功能与 Android Studio 不同。
可能会研究 SecureRandom -- 加密强随机数生成器 (RNG):https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html
另外,请参阅此 post 关于使用 SecureRandom 生成的随机数的长度: