Skip to content
March 30, 2012 / edeustace

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)
 if (uniqueFunc(newKey))
  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)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 93 other followers

%d bloggers like this: