简体   繁体   中英

Printing all possible combinations including duplicates, order matters too

I am trying to combine two sets (vectors) into one big that has all elements of both including duplicates.

for example:

setA = "abc" and setB has "12345" my output need to look like this:

{(a,1)(b,1)(c,1)}
{(a,1)(b,1)(c,2)}
{(a,1)(b,1)(c,3)}
{(a,1)(b,1)(c,4)}
{(a,1)(b,1)(c,5)}
{(a,1)(b,2)(c,1)}
{(a,1)(b,2)(c,2)}
{(a,1)(b,2)(c,3)}
{(a,1)(b,2)(c,4)}
{(a,1)(b,2)(c,5)}
{(a,1)(b,3)(c,1)}
{(a,1)(b,3)(c,2)}
.................    
{(a,5)(b,3)(c,5)}
{(a,5)(b,4)(c,1)}
{(a,5)(b,4)(c,2)}
{(a,5)(b,4)(c,3)}
{(a,5)(b,4)(c,4)}
{(a,5)(b,4)(c,5)}
{(a,5)(b,5)(c,1)}
{(a,5)(b,5)(c,2)} 
{(a,5)(b,5)(c,3)}
{(a,5)(b,5)(c,4)}
{(a,5)(b,5)(c,5)}

all 125 elements (5*5*5)

I tried to do this with for loop

    for (size_t i = 0; i < v_setB.size(); i++)
    {
        for (size_t k = 0; k < v_setB.size(); k++)
        {
            for (size_t n = 0; n < v_setB.size(); n++)
            {
                stringstream  temp;
                temp << "{(" << v_setA[0] << "," << v_setB[i] << ")(" << v_setA[1] << "," << v_setB[k] << ")(" << v_setA[2] << "," << v_setB[n] << ")}";
                v_SavedElem.push_back(temp.str());
            }
        }
    }

BUT if # of elements in first set grows then it will not work. Can some one help to create recursive function, please?

The function should take two sets (eg "abc" and "12345") as arguments, and produce the strings you describe.

So how about this: give it a third argument -- or better still make it the first -- that is a string to be used as a prefix for those strings. And another for the destination vector.

The function removes the first element from setA, and appends it to the prefix string. Then it iterates over the elements in setB, and either saves the results or calls the function again (with a shorter setA).

void foo(string pref, vector<char> v_setA, vector<char> v_setB, vector<string> &v_SavedElem)
{
  vector<char>::iterator itrA = v_setA.begin();
  pref += "(";
  pref += *itrA;
  pref+= ",";

  v_setA.erase(itrA);

  for(vector<char>::iterator itrB = v_setB.begin(); itrB!=v_setB.end(); ++itrB)
    {
      if(v_setA.empty())
      {
        stringstream  temp;
        temp << pref << *itrB << ")}" << endl;
        v_SavedElem.push_back(temp.str());
      }
      else
        foo(pref+*itrB+")", v_setA, v_setB, v_SavedElem);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM