Reputation: 73
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?
Upvotes: 2
Views: 2441
Reputation: 27421
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.
Upvotes: 6
Reputation: 3250
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
Upvotes: 1