RSS feed [root] /misc /weblog




login:

password:

title search:




 


Mon Jun 21 13:21:12 GMT 2021

Random unique integer number





Another notice about shuffling collection with random order - http://www.codinghorror.com/blog/archives/001008.html with detailed analysis- http://www.codinghorror.com/blog/archives/001015.html

unique => not statistically independent and not uniformly distributed,
cannot be generated by normal Random Number Generator.

You may consider way like shuffling (for example, put 100 integer into an
ArrayList, calls Collections.shuffle(), get the numbers sequentially).

Most of the time unique random number can be replaced by hashCode() of
something because hash seldom (at order of magnitude 10^-100 for MD5) crash,
if you don't require it to be "ALWAYS" unique, you may consider hashCode()
as well.



>> Hi Hi,
>>
>> I would like to write a method to generate a number of random and unique
>> number. I try to do it myself as following. It's work but seem to be
>> stupid.
>>
>> I try to found it at java.util.Random API but I didn't found out a better
>> solution. Please comment. Many thx
>>
>> Random generator = new Random();
>> Vector randomVec = new Vector();
>>
>> int r = 0;
>>
>> try {
>> do {
>> r = generator.nextInt(100);
>>
>> if (!randomVec.contains(new Integer(r).toString())) {
>> randomVec.addElement(new Integer(r).toString());
>> j++;
>> }
>> } while (j < 20);
>> } catch (Exception e) {
>> e.printStackTrace();
>> }


(google search) (amazon search)
second
download zip of files only