7
\$\begingroup\$

This is a verification code generator, which generates n-digit numeric strings. (code can be 0000, so I chose String as a return type rather than Int or Long.)

It'll be great if anyone review this code and suggest more elegant or scalaish solution.

import scala.util.Random

object VerificationCodeGenerator {
  val rand = new Random

  def generate(digit: Int): String = {
    val sb = new StringBuilder
    for (i <- 1 to digit) {
      sb.append(rand.nextInt(10))
    }
    sb.toString()
  }
}
\$\endgroup\$
8
\$\begingroup\$

if your number of digits is always going to be less than about 10, then you can use a single random operation and a string format, to do all the work without the loop.

Consider a method like:

def generate(digit: Int): String = {
    var randVal = rand.nextInt(math.pow(10, digit).toInt)
    var fmt = "%0" + digit + "d"
    fmt.format(randVal)
}

The randVal pulls a value with the limited number of digits (perhaps fewer than the limit). The format operation 0-pads the value to the right number, though.

This is not so much a scala way of doing it, but it is closer, and probably more efficient.

I would consider creating instances to handle each length of digits to avoid having to create the format each time, though.

See it running in ideone

\$\endgroup\$
  • 1
    \$\begingroup\$ In the general case, use either BigInteger or concatenate several generated strings. \$\endgroup\$ – 200_success May 7 '15 at 6:27
7
\$\begingroup\$

A shorter, more functional and perhaps more elegant way to do it is:

def generate(digits:Int):String = {
  (1 to digits) map(_=>rand.nextInt(10)) mkString("")
}

This code doesn't use a mutable object (StringBuilder).

One more way I can think of is:

def generate(digits:Int):String = {
  (for { i <- 1 to digits } yield rand.nextInt(10)) mkString("")
}

Slightly longer, essentially the same as first.

\$\endgroup\$
2
\$\begingroup\$

A concise and idiomatic solution:

def generate(digits: Int): String = 
  List.fill(digits)(rand.nextInt(10)).mkString
\$\endgroup\$
  • \$\begingroup\$ Iterator may give you slightly more performance than List. \$\endgroup\$ – SpiderPig May 8 '15 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.