-1

Possible Duplicate:
Random permutation of integers using a random number generator

For example I need to make a random number from 1 to 30. But it doesn't produce the same random number. The number produced has to be different one to another.

Is that possible?

Thanks

Community
  • 1
  • 1
  • 1
    You will need to keep a `List` of the numbers that have been produced so that if the random number is in that list, it tries again. – Devin Stewart Jan 05 '13 at 17:19
  • You can use the techniques in this Q&A: http://stackoverflow.com/questions/9052519/non-repeating-random-number-array – Mat Jan 05 '13 at 17:19
  • 1
    @DevinStewart: that's extremely inefficient. Think about the number of retries it would need to generate the 30th number. – JB Nizet Jan 05 '13 at 17:22
  • @JBNizet: True, if he is getting all 30 Numbers. I admit your solution is more efficient, hence up voted it. – Devin Stewart Jan 05 '13 at 17:26
  • @DevinStewart It'd be more efficient even if he's only getting two numbers. And more deterministic. – Dave Newton Jan 05 '13 at 17:27
  • @ Edward Octavianus Pakpahanplease note that if you want a number of desired value or characteristic then ITS NOT A RANDOM NUMBER! – codeMan Jan 05 '13 at 17:41
  • @codeMan A random number selected from the set {1, 20, 21, 25, 30} is just as much a random number as one selected from a set of consecutive numbers. All the question asks for is a number selected at random, with equal probability, from the subset of [1, ... ,30] that has not yet been selected. – Patricia Shanahan Jan 05 '13 at 17:49

1 Answers1

7

Create a List<Integer> containing 1-30, shuffle it using Collections.shuffle(), then iterate through the list. Of course, at the end of the list, it's impossible to have a new number that hasn't been generated yet.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255