asdawrqtgf
asdawrqtgf

Reputation: 640

Find all combinations without repetition

I have to find all combinations using 3 integers without repetition in C++ application.

I can calculate how many combination there are going to be when I specify how many integers do I have.

unsigned int combinations(unsigned int n){
    return ((n/3) * ((n-1)/2) * (n-2));
}

But how can I add to vector those all combinations? f.e using: 1,2,3,4: 123,234,124, 134. The order is not important and 123 is same as 321.

Upvotes: 3

Views: 2961

Answers (1)

Paul Draper
Paul Draper

Reputation: 83225

#include <vector>

using namespace std;

struct tuple3 {
    int a, b, c;   
    tuple3(int a, int b, int c) : a(a), b(b), c(c) {}
};

vector<tuple3> combinations3(vector<int> n) {
    vector<tuple3> ret;
    for(vector<int>::const_iterator it1 = n.begin(); it1 < n.end(); it1++) {
        for(vector<int>::const_iterator it2 = n.begin(); it2 < it1; it2++) {
            for(vector<int>::const_iterator it3 = n.begin(); it3 < it2; it3++) {
                ret.push_back(tuple3(*it1, *it2, *it3));
            }
        }
    }
    return ret;
}

To future readers: Use C++11 std::array or std::tuple if you can. I did not here because it is not yet available or default on many compilers.

Upvotes: 4

Related Questions