Reputation: 3621
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)
Upvotes: 0
Views: 1514
Reputation: 5519
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.
Upvotes: 1
Reputation: 809
you could populate the range into an array and shuffle the array. This would be inefficient though for very large ranges
Upvotes: 1
Reputation: 10871
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.
Upvotes: 1
Reputation: 86774
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
Upvotes: 3