Answer to Question #321219 in C++ for Christian

Question #321219

A code is required to print all possible arrangement of combination of an array(of 'k' elements), i.e. the permutation of the result of combination.



Let's say the array has the following elements (k=4):


"alpha", "beta", "gamma", "delta".


Then, we choose r=3


The expected result is as follows:



alpha beta gamma


alpha gamma beta


beta alpha gamma


beta gamma alpha


gamma alpha beta


gamma beta alpha


alpha beta delta


alpha delta beta


beta alpha delta


beta delta alpha


delta alpha beta


delta beta alpha


alpha delta gamma


alpha gamma delta


delta alpha gamma


delta gamma alpha


gamma alpha delta


gamma delta alpha


beta delta gamma


beta gamma delta


delta beta gamma


delta gamma beta


gamma beta delta


gamma delta beta



From the above result above, all unique PERMUTATION of the COMBINATION of r=3 from the array of k=4 elements is completed.



This is confirmed since 4C3 x 3! = 24 lines of results



1
Expert's answer
2022-04-18T08:41:43-0400
#include <iostream>
#include <vector>
#include <string>


using namespace std;


void print_permutation(vector<string>& from, int r, vector<string>& perm) {
    if (r == 0) {
        for (size_t i=0; i<perm.size(); i++) {
            cout << perm[i] << " ";
        }
        cout << endl;
        return;
    }

    for (auto it=from.begin(); it!=from.end(); ++it) {
        perm.push_back(*it);
        vector<string> v;
        v.insert(v.begin(), from.begin(), it);
        v.insert(v.end(), it+1, from.end());
        print_permutation(v, r-1, perm);
        perm.pop_back();
    }
}

int main() {
    vector<string> v = {"alpha", "beta", "gamma", "delta"};
    vector<string> perm;

    print_permutation(v, 3, perm);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog