I have to Generate a 6 digit Random Number. The below is the Code that I have done so far. It works fine but some time its giving 7 digits in place of 6 digits.
The main question is why?
How do I generate an assured 6 digit random number?
val ran = new Random()
val code= (100000 + ran.nextInt(999999)).toString
If ran.nextInt()
returns a number larger than 900000
, then the sum will be a 7 digit number.
The fix is to make sure this does not happen. Since Random.nextInt(n)
returns a number that is less than n
, the following will work.
val code= (100000 + ran.nextInt(900000)).toString()
It's because nextInt()
Returns a pseudorandom, uniformly distributed int
value between 0 (inclusive) and the specified value (exclusive)
You have to decrease your right border on one.
val code= (100000 + ran.nextInt(999999)).toString
The problem is ran.nextInt(999999)
might return number greater than 899999, which would result in 7-digit-number together if you add 100000.
Try change it to
val code= (100000 + ran.nextInt(899999)).toString
This will ensure your random number to be more than or equal to 100000 and less than or equal to 999999.
Another approach, for
import scala.util.Random
val rand = new Random()
consider a vector of 6
random digits,
val randVect = (1 to 6).map { x => rand.nextInt(10) }
Then, cast the vector onto an integral value,
randVect.mkString.toLong
This proceeding is general enough to cope with any number of digits. If Long
cannot represent the vector, consider BigInt
.
Update
Moreover, wrap it into an implicit class, noting that the first digit ought not be zero,
implicit class RichRandom(val rand: Random) extends AnyVal {
def fixedLength(n: Int) = {
val first = rand.nextInt(9)+1
val randVect = first +: (1 until n).map { x => rand.nextInt(10) }
BigInt(randVect.mkString)
}
}
so it can be used as
scala> rand.fixedLength(6)
res: scala.math.BigInt = 689305
scala> rand.fixedLength(15)
res: scala.math.BigInt = 517860820348342
If you want a random number which can start with zeros, consider this:
import scala.util.Random
val r = new Random()
(1 to 6).map { _ => r.nextInt(10).toString }.mkString
Starting Scala 2.13
, scala.util.Random
provides:
def between(minInclusive: Int, maxExclusive: Int): Int
which used as follow, generates a 6-digit Int
(between 100_000
(included) and 1_000_000
(excluded)):
import scala.util.Random
Random.between(100000, 1000000) // in [100000, 1000000[
import scala.util.Random
math.ceil(Random.nextFloat()*1E6).toInt
min=100000
max=999999
ans=rand()%(max-min)+min