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 all possible N combinations of X characters in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
 
std::vector<char> combination;
 
void print(const std::vector<char>& 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<char>& characters, int start, int Ncombinations) {
    if (Ncombinations == 0) {
        print(combination);
        return;
    }
    for (int i = start; i <= characters.size() - Ncombinations; i++) {
        combination.push_back(characters[i]);
        generate(characters, i + 1, Ncombinations - 1);
        combination.pop_back();
    }
}
 
int main() {
    int X_1_to_6 = 6, Ncombinations = 3;
 
    std::vector<char> characters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
   
    generate(characters, 0, Ncombinations);
 
    return 0;
}
 
 
 
 
/*
run:
   
a b c 
a b d 
a b e 
a b f 
a b g 
a c d 
a c e 
a c f 
a c g 
a d e 
a d f 
a d g 
a e f 
a e g 
a f g 
b c d 
b c e 
b c f 
b c g 
b d e 
b d f 
b d g 
b e f 
b e g 
b f g 
c d e 
c d f 
c d g 
c e f 
c e g 
c f g 
d e f 
d e g 
d f g 
e f g 
   
*/

 



answered Sep 30, 2021 by avibootz
...