Hi !
Featured games (84)
games approved by the League of Dukes
Games in Showcase (564)
Games in Android Showcase (151)
games submitted by our members
Games in WIP (605)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Generating unique random numbers.  (Read 1867 times)
0 Members and 1 Guest are viewing this topic.
Offline ShannonSmith
« Posted 2011-08-01 04:59:45 »

My current project involves a lot of procedural generation and I can't come up with a good way of generating a set of unique random numbers. Say I had to pick N random numbers between A and B with the guarantee of no duplicates how would you go about it? Keeping in mind N and B could be arbitrarily large discounting the inelegant obvious solution.
Offline Scarzzurs
« Reply #1 - Posted 2011-08-01 07:18:04 »

You could try generating a list with numbers A to B and drawing from it randomly (removing the element).

Or, you can pre-generate and shuffle the list in order to avoid the cost generating randomness later.
The shuffle method of the Collections class runs in linear time, so it should work even for large lists.

I suppose an ArrayList with predefined capacity would be a good choice for the storage in either case.

Hope these methods are adequate :-)

- Scarzzurs

My games and Projects:,
Old website
Offline philfrei
« Reply #2 - Posted 2011-08-01 07:58:22 »

Generate random number, put it into a HashSet (an unordered collection that rejects duplicates). If it is allowed into the HashSet, it is unique, and thus can be used.

If it DOESN'T go in, you could just generate another and try again, but there's no guarantee you will ever succeed in creating your set!

So, instead of that, try incrementing the number that collided and keep trying until you succeed. It seems to me a simple increment by 1 is OK, but it might be better to pick a large prime number that is not a factor of the size of the sample set, so that it jumps around more. The main thing is that whatever your increment, it should guarantee eventually touching each possible value. Then, as long as N is smaller than B-A, you are guaranteed of completing the task.

For example, if you sample set is 121, you wouldn't want to use an increment of 11, but 7 or 13 would be fine.

"We all secretly believe we are right about everything and, by extension, we are all wrong." W. Storr, The Unpersuadables
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Jono
« Reply #3 - Posted 2011-08-01 09:30:56 »

It might be easier to first generate an ordered list of N unique numbers that are between A and B, and then take randomly from that (or shuffle it after it is generated).

The ordered list can then be thought of as N+1 "gaps" between each number, where each gap is >= 1 and the sum of the gaps is B-A. If you can work out what the probability of each gap size is then you could create the list recursively:

List gaps(int n, int a, int b){
  if(n == 1)
      return {random(b-a)};
  int nextGap = randomGap(n,a,b);
  return {nextGap} + gaps(n-1,a+nextGap,b);

I don't know what the probability distribution of "randomGap" should be but I bet a statistician or wikipedia will.
Offline nsigma
« Reply #4 - Posted 2011-08-01 09:52:31 »

Keeping in mind N and B could be arbitrarily large discounting the inelegant obvious solution.

What inelegant obvious solution do you actually have in mind???  Just wondering if that was a HashSet from JDK because of object overhead, or the brute force approach, or something else?  If HashSet you could consider philfrei's post but use one of the various HashSet solutions that work directly with primitives.

Praxis LIVE - open-source intermedia toolkit and live interactive visual editor
Digital Prisoners - interactive spaces and projections
Offline ShannonSmith
« Reply #5 - Posted 2011-08-01 17:22:02 »

Inelegant would be anything where you can't predict how long the algorithm will run (such as re-picking on collisions). Generating the complete set from A to B, shuffling and selecting the first N would be fine for a small set but B can be arbitrarily large.
Offline Riven
« League of Dukes »

« JGO Overlord »

Medals: 947
Projects: 4
Exp: 16 years

Hand over your head.

« Reply #6 - Posted 2011-08-01 17:40:46 »

You can easily implement two strategies:

If there are few possible values, use a list and shuffle it, if it's big, use a set of values already returned.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
Offline pjt33

« JGO Spiffy Duke »

Medals: 39
Projects: 4
Exp: 7 years

« Reply #7 - Posted 2011-08-01 22:38:41 »

On the assumption that B >> N:

Take a self-balancing tree which gives a count of the size of each subtree. Store the numbers already picked in the tree. To generate a new number:

int x = A + rnd.nextInt(B - A + 1 - tree.size());
int skipped = 0, skip = 0;
while ((skip = tree.countLE(x)) > skipped) {
    x += skip - skipped;
    skipped = skip;
return x;

If you're worried about long runs of taken numbers, you could complicate things even more...
Pages: [1]
  ignore  |  Print  
You cannot reply to this message, because it is very, very old.

wxwsk8er (50 views)
2015-03-20 15:39:46

Fairy Tailz (42 views)
2015-03-15 21:52:20

Olo (28 views)
2015-03-13 17:51:59

Olo (29 views)
2015-03-13 17:50:51

Olo (33 views)
2015-03-13 17:50:16

Olo (40 views)
2015-03-13 17:47:07

ClaasJG (29 views)
2015-03-10 11:36:42

ClaasJG (37 views)
2015-03-10 11:33:01

Pippogeek (45 views)
2015-03-05 14:36:23

Pippogeek (37 views)
2015-03-05 13:56:12
How to: JGO Wiki
by Mac70
2015-02-17 20:56:16

2D Dynamic Lighting
by ThePixelPony
2015-01-01 20:25:42

How do I start Java Game Development?
by gouessej
2014-12-27 19:41:21

Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27 is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!