Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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()
  }
}
share|improve this question

2 Answers 2

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

share|improve this answer
1  
In the general case, use either BigInteger or concatenate several generated strings. –  200_success 22 hours ago

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 don't use mutable object(StringBuilder).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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