Guaranteed 6-digit random number

I need to create a 6 digit random number. Below is the Code I have made so far. It works great, but for a while it gives 7 digits instead of 6 digits .

The main question is: why?

How to create a guaranteed 6-digit random number?

val ran = new Random()
val code= (100000 + ran.nextInt(999999)).toString
+5
source share
8 answers

If it ran.nextInt()returns a number greater than 900000, then the sum will be a 7-digit number.

Fix this to make sure this does not happen. Since it Random.nextInt(n)returns a lower number, the nfollowing will work.

val code= (100000 + ran.nextInt(900000)).toString()
+11

, nextInt() int 0 () ()

.

+3
val code= (100000 + ran.nextInt(999999)).toString

ran.nextInt(999999) 899999, 7- , 100000.

val code= (100000 + ran.nextInt(899999)).toString

, 100000 999999.

+3

,

import scala.util.Random
val rand = new Random()

6 ,

val randVect = (1 to 6).map { x => rand.nextInt(10) }

,

randVect.mkString.toLong

, . Long , BigInt.

, , , ,

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)
  }
}

scala> rand.fixedLength(6)
res: scala.math.BigInt = 689305

scala> rand.fixedLength(15)
res: scala.math.BigInt = 517860820348342
+2

, , :

import scala.util.Random
val r = new Random()
(1 to 6).map { _ => r.nextInt(10).toString }.mkString
+1
import scala.util.Random
math.ceil(Random.nextFloat()*1E6).toInt
0

Scala 2.13, scala.util.Random :

def between(minInclusive: Int, maxExclusive: Int): Int

, 6- Int ( 100_000 () 1_000_000 ()):

import scala.util.Random
Random.between(100000, 1000000) // in [100000, 1000000[
0
    min=100000
    max=999999
    ans=rand()%(max-min)+min
-1

Source: https://habr.com/ru/post/1540319/


All Articles