Search code examples
crecursion

Combination of two strings


I'm doing C course on my university, and i think that i'm still stuck on JAVA, because i can't get the next code (Recursion):

#include <stdio.h>
#include <conio.h>
#define N 11

int Combination(char *, char *, char *);
void main(){
int i;
char *S1[]={"","abc","abc","abc","abc","ab c","morning Venm","ABZ","12189","12189",      
    "TTTT"},

     *S2[]={"", "", "def", "def", "def", "def", "Good ita!", "ABAXZ", "129", "129", 
     "X"},

     *S3[]={"", "abc", "abcdef", "daebcf", "adfbce", "deab cf","Good morning Vietnam!",
            "ABAXABZZ", "12181299", "12112998", "XXXXX"};

for(i=0;i<N;i++){
    if(Combination(S1[i],S2[i],S3[i])) 
         printf("S1: \"%s\", S2: \"%s\", S3: \"%s\", 
         Combination!\n",S1[i],S2[i],S3[i]);
    else printf("S1: \"%s\", S2: \"%s\", S3: \"%s\", Not a 
         Combination!\n",S1[i],S2[i],S3[i]);

}

_getch();
}

/*Function name : Combination
  Input : address of three strings
  Output : true(1) if the third string is a combination of the two firsts strings,    
          false (0) if not
  Algorithm : check if the third string is made from the letters of the first and  
              second strings*/
int Combination(char *S1, char *S2, char *S3)
{
    if(!*S1 && !*S2 && !*S3) return 1;
    if(*S3==*S1 && *S3==*S2)
        return (Combination(S1+1,S2,S3+1)||Combination(S1,S2+1,S3+1));
    if(*S3==*S1) return Combination(S1+1,S2,S3+1);
    if(*S3==*S2) return Combination(S1,S2+1,S3+1);
    return 0;
}

I want to understand any line on the Combination method.

1) if(!*S1 && !*S2 && !*S3) = that check if the 3 Strings are null ?

2) what the part of: (S1+1,S2,S3+1) - what that doing? S1+1 will give us the next word on the array or it will give the next letter ? if it will give us the next letter - for what? it's already cheked if the strings are equal?

I'm confused...

  • I got the recursion, but not the part of S1+1\S2+1\S3+1...

Solution

  • *S1 is the first character of string S1, so

    if (!*S1 && !*S2 && !*S3) 
    

    is checking to see if the first character of all three strings is null, which means they are all empty strings.

    S1+1 is effectively string S1 with the first character removed. Strings are passed around in C by passing a pointer to the first character. By passing S1+1, the beginning of the string is moved down one character.