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