Generate all possible combinations with recursion

Viewed 243

I want to generate all possible combinations using recursion, came up with a solution in python but don't know how to implement it in C.

def combinations(text):
    if "?" in text:
        for char in "abc":
            combinations(text.replace("?", char, 1))
    else:
        print(text)
combinations("???")

Which gives us all possible combinations of length 3 using abc.

My C code looks something like this but it does not work as it should be.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char chars[4] = "abc";

void combinations(int repeat, char *result){
    if (repeat--){
        for (int i = 0; i < 3; i++){
            result[strlen(result)] = chars[i];
            combinations(repeat, result);
        }
    }
    else{
        printf("%s\n", result);
        result[0] = '\0';
    }
}

int main(){
    char *res = (char *)malloc(2000);
    combinations(3, res);
}

What I expect is that it outputs every possible unique combination of length 3 using abc:

aaa
aab
aac
aba
...

What C code outputs are:

aaa
baa
caa
baaa
...
0 Answers
Related