Assured 6 digit random number

2019-04-08 20:13发布

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

8条回答
我命由我不由天
2楼-- · 2019-04-08 20:48

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[
查看更多
Emotional °昔
3楼-- · 2019-04-08 20:50

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
查看更多
等我变得足够好
4楼-- · 2019-04-08 20:54

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()
查看更多
做个烂人
5楼-- · 2019-04-08 20:55

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
查看更多
ら.Afraid
6楼-- · 2019-04-08 21:02
    min=100000
    max=999999
    ans=rand()%(max-min)+min
查看更多
该账号已被封号
7楼-- · 2019-04-08 21:04

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.

查看更多
登录 后发表回答