Scala – generate random alphanumeric sequence
For Scala Puzzles I need to create a random sequence to allow people to link to anonymous puzzles. I found an example here, but it was using toString instead of mkString, so I’ve tweaked it a tiny bit (gist is here)
import scala.util.Random
def uniqueRandomKey(chars: String, length: Int, uniqueFunc: String=>Boolean) : String =
{
val newKey = (1 to length).map(
x =>
{
val index = Random.nextInt(chars.length)
chars(index)
}
).mkString("")
if (uniqueFunc(newKey))
newKey
else
uniqueRandomKey(chars, length, uniqueFunc)
}
/**
* implement your own is unique here
*/
def isUnique(s:String):Boolean = true
val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') ++ ("-!£$")
val key = uniqueRandomKey(chars.mkString(""), 8, isUnique)
println(key)
