0

I used the following code to generate the random numbers:

long randNo = Math.round(Math.random() * 10000);

I have some situations where i found duplicates. Is it possible that it will generate same numbers?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Biswajit das
  • 99
  • 1
  • 11
  • ref http://stackoverflow.com/questions/4655931/12-digit-unique-random-number-generation-in-java – Salil Oct 15 '12 at 07:31
  • 5
    You don't seem to understand what "random" means. – Brian Roach Oct 15 '12 at 07:31
  • 3
    Ofcourse it is possible that it will generate the same numbers. Randomness and uniqueness are two totally different things. – Jesper Oct 15 '12 at 07:31
  • 7
    Counter-question: if you execute this line of code 10001 times, what is the chance that it **doesn't** produce a duplicate value at least once? – Joachim Sauer Oct 15 '12 at 07:32

2 Answers2

2

Yes, it's possible. If you need to generate 10000 distinct random numbers from 0 to 9999. You can generate list of 10000 consecutive numbers and then call Collections.shuffle on it.

Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
1

With random numbers, all numbers in the range are equally likely. This means if you get a number, the next value is just as likely to appear as it did the first time.

BTW: using round is not a great idea in you example as the numbers 1 to 9999 are equally likely but the numbers 0 and 10000 are half as likely as they only occur on a half rounded down or half rounded up.

A more efficient pattern is to use

Random rand = new Random();

// as needed
int num = rand.nextInt(10000); // will be [0, 10000)

If you need to generate unique numbers you can use Collections.shuffle

List<Integer> nums = new ArrayList<Integer>();
for(int i = 0; i < 10000; i++) nums.add(i);
Collections.shuffle(nums);

This will give you up to 10000 unique numbers in a random order.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130