-1

Consider the case of having three arrays:

X = {A , B , C};
Y = {D , E , F};
Z = {G , H , I};

How to generate all the possible combinations from these three arrays ( C++ or Python ), that's like

C1 = {A , D , G};
C2 = {A , D , H};
...
C4 = {A, E , G};
...
C10 = {B , D , G};
...
...
Omar Farrag
  • 177
  • 1
  • 2
  • 11
  • I think you are looking for cartesian product. Look here .https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists – Alex Sep 04 '17 at 01:37
  • @Tico Thank you This is exactly what I was looking for.. If there is a c++ implementation it would be great too. – Omar Farrag Sep 04 '17 at 01:49
  • @Julien Thank you This is exactly what I was looking for.. If there is a c++ implementation it would be great too. – Omar Farrag Sep 04 '17 at 01:50

3 Answers3

2

Try this

from itertools import product

x = {'a', 'b', 'c'}
y = {'d', 'e', 'f'}
z = {'g', 'h', 'i'}

for a in product(x, y, z):
    print(a)

If you want to be more down-to-earth, getting all combinations from multiple sets can be done by nested loops. In python, it would be like this

for e1 in x:
    for e2 in y:
        for e3 in z:
            print((e1, e2, e3))

If you do not know how many iterables exist beforehand, you can keep appending them into a list as the program runs, then run product(*args), for example

items = [x, y]
items.append(z)
for a in product(*items):
    print(a)
nos
  • 19,875
  • 27
  • 98
  • 134
0

You can use Algorithm header inside STL, Using next_permutation function you can generate all possible combination. Caution: It will only generate one permutation, You will have to use it inside a loop. You can see the documentation for the function on this link.Generating Permutation

SS7
  • 84
  • 3
0

The "combination" function works recursively to find the answer. Just put all your elements in an array called "arr" which I considered that has the size of 6. Below is an example on haw to use the function:

#include <iostream>
#include <vector>
using namespace std;


void combinations(string arr[], int len, int startPosition, string result[]){
    if (len == 0){
        cout <<"{";
        for (int i = 0; i < 2; i++) {
            cout << result[i] <<", ";
        }
        cout << result[2]+ "}" << endl;
        return;
    }

    for (int i = startPosition; i <= 6-len; i++){
        result[3 - len] = arr[i];
        combinations(arr, len-1, i+1, result);
    }
}

int main(int argc, const char * argv[]) {

    string arr[] = {"A","B","C","D","E","F"};
    string temp[3];
    combinations(arr, 3, 0, temp);

}
reza karimi
  • 164
  • 1
  • 8