1

I have an assignment to write code that printing all combinations of N char. For example, if the input is 3, the expected output must be "aaa aab aac aba ... ccc". But my code looping over and over again. Here's my code.

#include <stdio.h>

#ifndef MAX
#define MAX 5
#endif

void comb(char kar[], int size, int index) {
    // string = aaa
    // lim = 'd'
    char lim = 'a' + size;
    while (index != -1) {

        if (kar[size-1] != lim) { // != c
            for (int i = 0; i < size; i++) {
                printf("%s ", kar);
                kar[size-1]+=1;
            }
            return comb(kar, size, index);

        } else {

            while (kar[index-1] == lim && index != -1) {
                kar[index-1]='a';
                index--;
            }
            kar[index-1] += 1;

            return comb(kar, size, size);
        }
    }
}

int main(int argc, char const *argv[]) {
    int n;
    char kar[MAX];

    printf("Input N char : ");
    scanf(" %d", &n);

    for (int j = 0; j < n; j++) {
        kar[j] = 'a';
    }

    comb(kar, n, n);

    return 0;
}

I'm a little bit confused and I have no idea where is the mistake. Thank you.

3
  • 2
    OT: Hint: dont write 97 but 'a'. It's mor ereadable and clearly shows your intention. Commented Apr 21, 2020 at 11:51
  • Slightly OT: zero initialize the kar array like this: char kar[MAX] = { 0 };, otherwise you will most likely print garbage. Commented Apr 21, 2020 at 11:58
  • 2
    You only ever pass n, index, and size as the index argument, and you never assign to it within comb, so it's hard to see how index != -1 could ever become false. Commented Apr 21, 2020 at 12:34

1 Answer 1

1

The problem has been solved. I changed some elements in the comb() and added the pow() function to define the recursion limit.

int comb(char kar[], int size, int index, int limit) {

    char lim = 97 + size;
    int limit_value = pow(size,size);
    if(limit == limit_value){
        return 1;

    } else {

        if (index < size-1) {
            printf("%s ", kar);
            kar[size-1]+=1;
            return comb(kar, size, index+1, limit+1);

        } else {
            int cek = index;
            printf("%s ", kar);
            while (kar[cek] == lim-1 ) {
                kar[cek]=97;
                cek-=1;
            }
            kar[cek] += 1;

            return comb(kar, size, 0, limit+1);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.