Can anyone help me with this?
Sep 21, 2014 at 6:59pm UTC
The code Below works just fine.. it will print all combinations from number 1 to 25, in and array of 15 numbers.
The thing is, I need to make it print only the combinations which the sum of all the elements divided by 15 is between 13 and 14. Can anyone help?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
#include <vector>
using namespace std;
vector<int > people;
vector<int > combination;
void pretty_print(const vector<int >& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ " ;
for (int i = 0; i < v.size(); ++i) { cout << v[i] << " " ; }
cout << "] " << endl;
}
void go(int offset, int k) {
if (k == 0) {
pretty_print(combination);
return ;
}
for (int i = offset; i <= people.size() - k; ++i) {
combination.push_back(people[i]);
go(i+1, k-1);
combination.pop_back();
}
}
int main() {
int n = 4, k = 3;
for (int i = 0; i < n; ++i) { people.push_back(i+1); }
go(0, k);
return 0;
Sep 21, 2014 at 7:36pm UTC
Add another check before calling pretty_print. Something like:
1 2 3 4 5 6
if (k == 0) {
double sum = std::accumulate(combination.begin(), combination.end(), 0) / 15.0;
if (sum >= 13 && sum <= 14 )
pretty_print(combination);
return ;
}
Sep 21, 2014 at 8:21pm UTC
thanks!
Topic archived. No new replies allowed.