• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help needed to generate a unique random number without importing any third party jar's.  RSS feed

 
Amith Bhavikatti
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I want to generate unique random number from(0 to n number) such that if i run the program everytime it should give me a unique random number all the time.numbers should not repeated at any cost.

Please help me...

Thanks in Advance..
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do it by using Math.random method. You have to maintain a list of all the numbers you have generated and used. Before returning the random number you have to check that it is already present in the list or not? If it is in list then you have to generate the function again.

HTH
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Set would be more suitable instead of a list.
 
Campbell Ritchie
Marshal
Posts: 56560
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are supposed to call this random sampling from a declining population, or something similar. Please do a search of this forum; similar questions are asked about 6-10 times a year, and there will probably be helpful suggestions in the old threads.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maneesh Godbole wrote:A Set would be more suitable instead of a list.

For what HG suggested, yes. However there's another algorithm using a List and Collections.shuffle(); this works quite well as long as N is not too large.
 
Amith Bhavikatti
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys for your answers.

I Hope it works.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12564
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you also need to thnk about what you will do when your program is run the (n+1)th time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!