June 29, 2011

String Combination

Question: Write a program to display all combinations of alphabets  in a given string ? For example: string 'xyz' has following possible combinations:
x
xy
xyz
xz
y
yz
z

// initial call: combinations("xyz", 0, 0)
void combinations(char *str, int start, int level)
{
    int i = 0;
    int len = strlen(str);
    if (start == len) {
        // Termination Condition
        return;
    }

    for(i = start; i < len; i++)
    {
        output[level] = str[i];
        output[level + 1] = '\0';
        printf("%s\n", output);
        combinations(str, i + 1, level + 1);
    }
}

1 comment:

  1. saves one extra function call overhead at the end of the string:

    void combinations(char *str, int start, int level)
    {
    int i = 0;
    int len = strlen(str);
    for(i = start; i < len; i++)
    {
    output[level] = str[i];
    output[level + 1] = '\0';
    printf("%s\n", output);
    if(i+1<len)
    combinations(str, i + 1, level + 1);
    }
    }

    ReplyDelete