Possibles Combinations of Alphabet in C

Discussion in 'C' started by Sundown G, Feb 13, 2012.

  1. Sundown G

    Sundown G New Member

    Joined:
    Feb 13, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi people I'm programming in C like a month. I just made this code yesterday, but I want the same result with a better code without using recursion for optimization, i think mine is sloppy. Also im using linux distribution... Any ideas to change this code in 1 or 2 functions?

    Anything will help! Thanks.

    Code:
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    #define Plain "plain.txt" 
    
    
    int length ;
    int i;
    char alphalower[] = "abcdefghijklmnopqrstuvwxyz"; 
    
    
    int main(){
    
        printf("\tEnter Maximum Char Length: ");
        scanf("%d",&length);
        for(i=1;i<=length;i++){
            combinations(alphalower,i);
        }
       return 0;
    
    }
    
    int possibles (const void * a, const void * b)
    {
        return ( *(char *)a - *(char *)b );
    }
    void back2 (char *str, char* info, int last, int index)
    {
        FILE *fp;
        if ((fp = fopen(Plain, "a+")) == NULL)
        {
            perror (Plain);
            exit (EXIT_FAILURE);
        }
        int i, length = strlen(str);
        for ( i=0; i < length; i++ )
        {
            info[index] = str[i] ;
            if (index == last)
                fprintf(fp,"%s\n", info);
            else 
                back2 (str, info, last, index + 1);
        }
        fclose(fp); 
    
    }
    
    int combinations(char *str, int length)
    {
    
        char *info = (char *) malloc (sizeof(char) * (length + 1)) ;
        info[length] = '\0';
        qsort(str, length, sizeof(char), possibles);
        back2 (str, info, length-1, 0);
        free(info);
    
        return 0;
    }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice