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)
     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)

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

Join 83 other followers

%d bloggers like this: