patternMinor
Random 6 to 10 digits number
Viewed 0 times
randomdigitsnumber
Problem
I am generating a random numerical 6-10 digit password. I need some important reviews of yours. Is it OK or are there some needed modifications?
val AB = "0123456789669900"
val rnd = new Random()
def randomNumericalString(): String = {
val len = rnd.nextInt(5) + 5
val sb = new StringBuilder(len)
for (i <- 0 to len)
sb.append(AB.charAt(rnd.nextInt(AB.length())))
return sb.toString
}Solution
Your algorithm makes the probabilities of some numbers much higher than other numbers. Is this intentional? For example, 0 will appear 3 times as often as 1. It would be better to simply have the input string
The range you supply in your for-loop is confusing, the requirements are for 6 digits, but, you use the magic-number 5. in the random. Consider using:
That is enough of an answer, on it's own, but I would suggest you consider the following. It is a little flawed in the sense that it never generates a value with a 0 as the first character.... I was part way through the answer when I realized this, but thought you should consider the approach anyway:
The above will generate a random number, with uniform distribution, between 100000 and 9999999999 (and here, as an ideone )
"0123456789" and have the uniform distribution.The range you supply in your for-loop is confusing, the requirements are for 6 digits, but, you use the magic-number 5. in the random. Consider using:
val shortest = 6
val longest = 10
val len = shortest + rnd.nextInt(longest - shortest + 1)
for (i <- 1 to len)That is enough of an answer, on it's own, but I would suggest you consider the following. It is a little flawed in the sense that it never generates a value with a 0 as the first character.... I was part way through the answer when I realized this, but thought you should consider the approach anyway:
def randomNumericalString(): String = {
return ((100000.0 + rnd.nextDouble() * (10000000000.0 - 100000.0)).toLong).toString
}The above will generate a random number, with uniform distribution, between 100000 and 9999999999 (and here, as an ideone )
Code Snippets
val shortest = 6
val longest = 10
val len = shortest + rnd.nextInt(longest - shortest + 1)
for (i <- 1 to len)def randomNumericalString(): String = {
return ((100000.0 + rnd.nextDouble() * (10000000000.0 - 100000.0)).toLong).toString
}Context
StackExchange Code Review Q#55098, answer score: 4
Revisions (0)
No revisions yet.