# Algorithm to find all possible combinations

• Hello,

I'm need to find every combinations following this explanation :

I have 4 lists :
1st list : (A,B)
2nd list (C,D)
3rd list (E,F)
4th list (G,H)

The result should be :

Only 1 from the first list
Only 1 from the second list
None to all from the third
Only one from the fourth list

Examples :
A + C+ G
A +C + E,F + H
B+ D + F + G

How can I find all those combinations ?
Not sure to be very clear here so if I'm not please ask me.

• Hi @DavidM29,

A very cheap (and probably slow, but that should not matter for such small lists) solution would be to have some nested for loops.

For the first, second and forth list you take one element per iteration.

Unfortuantely, for the third list you will have to take all possible combinations, which could be done by creating a temporary list C' (-; E; F; E, F) first. (don't know if you need F, E also?)

Regards

• @aha_1980
Thank you for your reply I'll do that. I don't need the F,E.

• @DavidM29
And make sure you end up with 32 combinations, exactly as per @aha_1980's algorithm :-;

BTW, my old favorite Prolog language would be better than C++ for this :) No loops!

• @JonB

BTW, my old favorite Prolog language would be better than C++ for this :) No loops!

I don't doubt that! However, even in C++ might be better approaches - my solution is a very simple one.

I'm sure deep in the STL or an external library there is an algorithm for such problems - but that's just outside my normal work area.