简体   繁体   中英

Scala Random Number Generator Not Producing Unique Random Numbers Between A Range

I have the following code to generate new random numbers

val start = 1
val end = 50000000
val rnd = new scala.util.Random

for (i < 1 to 25000000){
  val rnum = start + rnd.nextInt((end - start) + 1)

...
}

But this is producing duplicate random numbers now and again. Is this a bug or have I done something stupid?

Don't worry, this is not a bug, and you have not done anything stupid. However you have missed the fact that a sequence of random numbers can contain duplicates .

The reasons are explained in the comments.

The problem is that humans don't have a good instinctive understanding of random numbers. If you ask people to write a series of digits they are very unlikely to repeat a digit, even though this should happen 10% of the time. If you ask people to write down 5 random digits they are unlikely to use the same digit twice, even though this should happen 70% of the time.

There is no bug. It selects randomly so chances are there that same element would be picked. I prefer using the shuffle function of List.

val list = (1 to 100).toList

scala.util.Random.shuffle(list).take(1)

But creating a list of big number won't be an effective solution. You can use the following way to generate a random number.

val seed = new java.util.Date().hashCode
val rand = new scala.util.Random(seed)
val someNum = rand.nextInt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM