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,929 questions

51,862 answers

573 users

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

1 Answer

0 votes
#include <iostream>
#include <vector>
 
void printCombination(const std::vector<int>& vec, int size, int combinations, int resi, std::vector<int>& result, int veci) {
    if (resi == combinations) {
        for (int j = 0; j < combinations; j++) {
            std::cout << result[j] << " ";
        }
        std::cout << "\n";
        return;
    }
 
    if (veci >= size) {
        return;
    }
 
    result[resi] = vec[veci];
    printCombination(vec, size, combinations, resi + 1, result, veci + 1);
 
    printCombination(vec, size, combinations, resi, result, veci + 1);
}
 
void generateCombinations(const std::vector<int>& vec, int combinations) {
    std::vector<int> result(vec.size());
 
    printCombination(vec, vec.size(), combinations, 0, result, 0);
}
 
int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int combinations = 3;
 
    generateCombinations(vec, combinations);
}
 
   
   
/*
run:
     
1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5 
    
*/

 



answered Sep 24, 2024 by avibootz
edited Sep 24, 2024 by avibootz

Related questions

1 answer 157 views
1 answer 171 views
1 answer 94 views
1 answer 191 views
1 answer 132 views
1 answer 99 views
...