Win a copy of Mastering Corda: Blockchain for Java Developers this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

How to Generate Unique Random Numbers?

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
How to generate unique random numbers with out repetitions. i have a values between 1 to 9. i want to generate 5 unique random numbers from this 1 to 9. if i am using this code then it will generate a duplicate random numbers. Can any one please solve this problem and give me the solution code.
 
Ranch Hand
Posts: 266
 
Sheriff
Posts: 22054
113
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please Be Forthright When Cross Posting To Other Sites.

As for your problem, random automatically means non-unique. If you still need both, you will need to store all previous results and regenerate if you generated an existing number. This can cause infinite looping though, because the randomness cannot even guarantee that you will ever generate a new number.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Rob Prime:

As for your problem, random automatically means non-unique. If you still need both, you will need to store all previous results and regenerate if you generated an existing number. This can cause infinite looping though, because the randomness cannot even guarantee that you will ever generate a new number.



A solution that prevents this problem, and which works especially well for a small range of numbers:

- create an array with all the possible numbers, in your case one with the numbers from 1 to 9
- shuffle the array, using an ordinary random number generator
- use the first (or last) x numbers from the array as your unique random numbers
 
reply
    Bookmark Topic Watch Topic
  • New Topic