Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to generate all possible N combinations of X numbers in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
 
std::vector<int> combination;
 
void print(const std::vector<int>& v) {
    static int count = 0;
   
    for (int i = 0; i < v.size(); ++i) { 
        std::cout << v[i] << " "; 
    }
    std::cout << "\n";
}
 
void generate(const std::vector<int>& Xnumbers, int start, int Ncombinations) {
    if (Ncombinations == 0) {
        print(combination);
        return;
    }
    for (int i = start; i <= Xnumbers.size() - Ncombinations; i++) {
        combination.push_back(Xnumbers[i]);
        generate(Xnumbers, i + 1, Ncombinations - 1);
        combination.pop_back();
    }
}
 
int main() {
    int X_1_to_6 = 6, Ncombinations = 3;
 
    std::vector<int> Xnumbers;
 
    for (int i = 0; i < X_1_to_6; i++) { 
        Xnumbers.push_back(i + 1); 
    }
   
    generate(Xnumbers, 0, Ncombinations);
 
    return 0;
}
 
 
 
 
/*
run:
   
1 2 3 
1 2 4 
1 2 5 
1 2 6 
1 3 4 
1 3 5 
1 3 6 
1 4 5 
1 4 6 
1 5 6 
2 3 4 
2 3 5 
2 3 6 
2 4 5 
2 4 6 
2 5 6 
3 4 5 
3 4 6 
3 5 6 
4 5 6 
   
*/

 



answered Sep 30, 2021 by avibootz
edited Sep 30, 2021 by avibootz

Related questions

...