Combination

hello everyone i'm trying to make a combination of characters in c++
it goes something like that:
a
b
aa
ab
ba
bb
aaa
aab
aba
abb
baa
bab
bba
bbb
...
i just can't figure out how to code it's algorithm.
how about a vector of booleans, and a little logic..
insertr 1 (set false for a)
if all bits are not true, 'add' 1 (standard bit-wise integer addition here)
else set all to false and insert another one...
0
1 //add 1
00 //insert
01 //add 1
10 //add 1
11 //add 1
000 //insert

you can do this in an integer if you are not exceeding the # of bits in your biggest int.
you can do this as characters directly, but you have to understand the bit-wise addition and using 'a' and 'b' that way out of the ascii table. There are other ways to generate it as well; including a recursive buildup of previous values (new values are just a prefix on something you already found)

a aa prefix a, previous found 2 digit set
a ab
a ba
a bb

b aa prefix b, previous found 2 digit set.
b ab
b ba
b bb

a aaa //prefix a and first term of previous 3 digit set...
Last edited on
Or you could notice that it's a lot like counting in binary and do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

void print(unsigned n, unsigned size) {
    static const char symbol[] = "ab";
    for (unsigned mask = 1 << size; mask >>= 1; )
        std::cout << symbol[!!(n & mask)];
    std::cout << '\n';
}

int main() {
    for (unsigned sz = 1; sz <= 3; ++sz)
        for (unsigned n = 0; n < 1u << sz; ++n)
            print(n, sz);
}

Last edited on
Its the same as my first one, cleanly using the double for loop to do the 'insert' logic.
i'm coding a brute force attack it's not only for 'a' and 'b' i need to have all the alphabet with capital letters and numbers with infinite combinations to find the pass eventually
Using GMP (the snippet runs a small finite loop,
starting with a specific value and generating the next 4000 combinations):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <gmp.h>

int main()
{
    mpz_t n ;
    mpz_init_set_ui( n, 1'000'000'000 ); // start with GJDGXS (base 36)
    
    for( int i = 0 ; i < 4000 ; ++i ) // print the next 4000 combinations
    {
        // https://gmplib.org/manual/I_002fO-of-Integers.html#I_002fO-of-Integers
        mpz_out_str( stdout, -36, n ) ;
        
        if( i%20 == 19 ) puts("") ;
        else printf( "%s", "  " ) ;
        
        mpz_add_ui( n, n, 1 ) ; // add one to get the next number
    }
} 

http://coliru.stacked-crooked.com/a/c5a53190f30fc936
Registered users can post here. Sign in or register to post.