aspose file tools*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Combination Generation..." Watch "Combination Generation..." New topic
Author

Combination Generation...

Neville Mehta
Greenhorn

Joined: Feb 19, 2004
Posts: 1
Hi,
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
A B C
Now, we can have 3 (yes... 3C2) number of combinations if we take 2 at a time.
Those 3 would be
A B
B C
A C
---------------------------------------
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
Neville
Michael Dunn
Ranch Hand

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

Joined: Oct 02, 2003
Posts: 11422
    
  16

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,6
8,7,5
8,7,4
8,7,3
8,7,2
8,7,1 //inner loop done, increment middle loop...
8,6,5
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: http://aspose.com/file-tools
 
subject: Combination Generation...