Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# Combination Generation...

Neville Mehta
Greenhorn
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.
Neville

Michael Dunn
Ranch Hand
Posts: 4632
Not sure this is what you're after

fred rosenberger
lowercase baba
Bartender
Posts: 12085
29
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