jeudi 7 janvier 2016

Generate Random String/letter in Scala

I'm trying to generate a random String, and these are the possibilities I've found:

  1. Random.nextPrintableChar(), which prints letters, numbers, punctuation
  2. Random.alphanumeric.take(size).mkString, which prints letters and numbers
  3. Random.nextString(1), which prints Chinese chars almost every time lol

Random is scala.util.Random

size is an Int

The second option almost does the job, but I need to start with a letter. I found Random.nextPrintableChar() but it also prints punctuation.

What's the solution?

My solution so far was:

val low = 65 // A
val high = 90 // Z

((Random.nextInt(high - low) + low).toChar

Inspired by Random.nextPrintableChar implementation:

def nextPrintableChar(): Char = {
    val low  = 33
    val high = 127
    (self.nextInt(high - low) + low).toChar
  }




Aucun commentaire:

Enregistrer un commentaire