How to Generate a 4-digit Random Unique Number Using Kotlin?

Hello Friends Today, through this tutorial, I will tell you how to generate a 4-digit random unique OTP number using Kotlin Language Program?

Here’s how to generate a 4-digit random unique OTP number using Kotlin:

fun generateUniqueOTP(length: Int): String {
val charPool = "0123456789" // Define the pool of characters for the OTP
val random = Random()

val sb = StringBuilder()
for (i in 0 until length) {
val randomIndex = random.nextInt(charPool.length)
sb.append(charPool[randomIndex])
}

return sb.toString()
}

fun main() {
val otpLength = 4 // Set the desired length of the OTP
val uniqueOTP = generateUniqueOTP(otpLength)
println("Generated unique OTP: $uniqueOTP")
}

This code leverages the `Random` class for generating random numbers and a `StringBuilder` for efficient string construction. It ensures the generated OTP is unique by using a loop and random character selection.