This week's book giveaway is in the JDBC forum.
We're giving away four copies of Make it so: Java DB Connections & Transactions and have Marcho Behler on-line!
See this thread for details.
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 Make it so: Java DB Connections & Transactions this week in the JDBC 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: 11926

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
I agree. Here's the link:
subject: Combination Generation...
It's not a secret anymore!