Tuesday, June 25, 2013

Amazon Coding preparation test.Run Length Encoding and Decoding known as RLECompress


  1. Let us try Run Length Encoding and Decoding Today. If you have consecutive letters, then you can replace them with a macro that denotes the value. Macro starts with a Hash (#), followed by the letter that is repeated, followed by two digits representing repetition count. If RLE does not result in a compression, leave the text as is. Input string can be any letter, or number, or the symbols “<space> ~`:;'"!@#$%^&*()_-+=[]{}\|<>,.?/”
  2. String RLECompress(String input)
  3. Input: A, Output: A
  4. Input: AAAAAAABC, output #A07BC
    Note:-There are cases which do not looks obvious has been included take care of it.
    // Here is my program....... your comments will be welcome.
    #include <stdio.h>
    #include <string.h>
    void RLECompress(char Str[])
    {   char Result[1000];
        int i=1,temp=Str[0],count=0,n,j=0;
        n=strlen(Str);
        do
        {   if(Str[i]>=32&&Str[i]<=126||Str[i]=='\0'); 
           else if(temp!='\0'){printf("invalid string");return ;}
           if(Str[i]==temp&&count<100) count++;
            else
            {
                if(count!=0)
                {Result[j++]='#';
                     Result[j++]=temp;
                     Result[j++]=(count+1)/10+48;
                     Result[j++]=(count+1)%10+48;
                  }
                 else if(temp=='#')
                 {
                 Result[j++]='#';
                 Result[j++]=temp;
                 Result[j++]='0';
                 Result[j++]=count+49;
                 }
                 else 
                 {Result[j++]=temp;}
            count=0;
            temp=Str[i];
            }
            i++;
            
        }while(i<=n);
    Result[j]='\0';

    int m=strlen(Result);
    if(n>=m)
    printf("%s",Result);
    else
    printf("%s",Str);
    }

    int main(void)
    {
    char Str[]="AAAAAAAAAAAA~`:;'!!!!\"!!@#$%^&*()_-+=[]{}\|<>,.?/CDD";
    RLECompress(Str);
    return 0;
    }

No comments:

Post a Comment