patternMinor
n-digit Verification Code Generator
Viewed 0 times
codedigitgeneratorverification
Problem
This is a verification code generator, which generates n-digit numeric strings. (code can be
It'll be great if anyone review this code and suggest more elegant or scalaish solution.
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()
}
}Solution
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:
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
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
Code Snippets
def generate(digit: Int): String = {
var randVal = rand.nextInt(math.pow(10, digit).toInt)
var fmt = "%0" + digit + "d"
fmt.format(randVal)
}Context
StackExchange Code Review Q#90015, answer score: 8
Revisions (0)
No revisions yet.