开发者

random number generation and exclusion of the generated numbers

Is it possible to do this in Java ? I want to generate a random number such that given a range say f开发者_JAVA技巧or 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)


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


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.


you could populate the range into an array and shuffle the array. This would be inefficient though for very large ranges


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. 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜