Is it possible to do this in Java ? I want to generate a random number such that given a range say for example: between 1 and 70 - everytime the random number is generated it should be excluded from generation results.
so [1,70] rand = 56 (now 56 shouldn't be considered next time)
[1,70] = 63 (now 56,63 should be excluded from generation till my code runs)
Asked
Active
Viewed 1,504 times
0

phoenix
- 3,531
- 9
- 30
- 31
-
Duplicate to question : **[Java Creating Random Numbers with No Duplicates](http://stackoverflow.com/questions/4040001/java-creating-random-numbers-with-no-duplicates)** – lschin Apr 28 '11 at 03:42
4 Answers
3
This is equivalent to shuffling an array of numbers containing [1..70] and then dealing them out one at a time. Look up "shuffle algorithm" on Google. Here's a link http://www.vogella.de/articles/JavaAlgorithmsShuffle/article.html

Jim Garrison
- 85,615
- 20
- 155
- 190
-
1Or better use the shuffle algorithm that comes with JDK. http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List) – Aravind Yarram Apr 28 '11 at 03:47
-
1
I asked the same question here: How can I generate a random number within a range but exclude some?
The general strategy is something like filling an array with 70 values. Just remove the values that you randomly generate as per the link above.
1
you could populate the range into an array and shuffle the array. This would be inefficient though for very large ranges

A D
- 789
- 1
- 12
- 29
1
Another trivial alternative, using HashMaps to keep track of random numbers. It is sort of quick and dirty.
HashMap<Integer,Integer> hmRandomNum = new HashMap<Integer,Integer>();
Integer a = < generate random number>
if( hmRandomNum.get(a) == null)
{
hmRandomNum.put(a,a);
}
else
{
// ignore this random number. this was already selected and present in the hashmap.
}
//Iterate depending on how many numbers you want.

kensen john
- 5,439
- 5
- 28
- 36