I can generate a random sequence of numbers in a certain range like the following:
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> { (0..len-1).map { (low..high).random() }.toList() }
Then I'll have to extend List
with:
fun List<Char>.random() = this[Random().nextInt(this.size)]
Then I can do:
fun generateRandomString(len: Int = 15): String{ val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet() .union(CharArray(9) { it -> (it + 48).toChar() }.toSet()) return (0..len-1).map { alphanumerics.toList().random() }.joinToString("") }
But maybe there's a better way?
Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.
A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer.
Since Kotlin 1.3 you can do this:
fun getRandomString(length: Int) : String { val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9') return (1..length) .map { allowedChars.random() } .joinToString("") }
Lazy folks would just do
java.util.UUID.randomUUID().toString()
You can not restrict the character range here, but I guess it's fine in many situations anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With