Search code examples
kotlin

Idiomatic way to generate a random alphanumeric string in Kotlin


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?


Solution

  • Assuming you have a specific set of source characters (source in this snippet), you could do this:

    val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    java.util.Random().ints(outputStrLength, 0, source.length)
            .asSequence()
            .map(source::get)
            .joinToString("")
    

    Which gives strings like "LYANFGNPNI" for outputStrLength = 10.

    The two important bits are

    1. Random().ints(length, minValue, maxValue) which produces a stream of length random numbers each from minValue to maxValue-1, and
    2. asSequence() which converts the not-massively-useful IntStream into a much-more-useful Sequence<Int>.