wood burning stoves 2.0*
The moose likes Java in General and the fly likes Combination Generation... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Combination Generation..." Watch "Combination Generation..." New topic

Combination Generation...

Neville Mehta

Joined: Feb 19, 2004
Posts: 1
Could someone please refer me to some resource (or be nice enough to explain me here itself ), how we could generate unique combinations of a given set of objects (strings,integers.. whatever).
Say for eg. here is the set initially
Now, we can have 3 (yes... 3C2) number of combinations if we take 2 at a time.
Those 3 would be
A generic algo would be more helpful than an algo in java however even if someone posts an algo in java i could try and understand it myself. If you would be posting code, i request you to please send some little explaination if possible.
Thanks in advance
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
Not sure this is what you're after
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11167

If you're doing combinations, order doesn't matter, right? if you know how many elements you have, and how many you want to choose, you could do this...(i think this works)...
write as many nested loops as how many you want to choose. if you have 8 elements and want to choose 3, you'd have 3 nested loops.
note: i'm using english, so my elements are numbered 1-8, not 0-7
the outer loop would run from 8 to 4
the first inner loop would run from (outer value -1) to 2
the inner runs from (middle value -1) to 1
inside the inner most loop, you print the elements your on for each loop. you should get
8,7,1 //inner loop done, increment middle loop...
8,6,4... etc
i'm not sure how to do it completly generically, where you'd input the number of elelment and the number to choose... but i'm pretty sure it could be done recursively

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Don't get me started about those stupid light bulbs.
subject: Combination Generation...
Similar Threads
Generate string
key with combinations
permutation combination problem
Is this answer right?
Constructor doubts