Monday 23 September 2019

Little Boy is Uttering His First Words and Snake Procession Code chef solution in C

Little Boy is uttering his first words. If there is sub sequence mom in the words he uttered, print Mom and if it contains sub sequence dad print Dad and if it has both print the one that whose sub sequence has occurred first. If it has no words at all, print Goo-goo

Program:
#include<stdio.h>

int main() {
    char st[100],s1[]="mom",s2[]="dad";
    scanf("%s",st);
    int i,j=0,k=0;
 
    for(i=0;st[i]!='\0';i++)
    {
        if(st[i] == s1[j])
        {
            j++;
            if(j==3)
                break;
        }
        if(st[i] == s1[k])
        {
            k++;
            if(k==3)
                break;
        }
    }
    if(j==3)
        printf("Mom");
    else if(k==3)
        printf("Dad");
    else
        printf("Goo-goo");
 
        return 0;

}

here in order to check whether a sub sequence is present or not in a given string, the best way to check is given in the above program.
Also once we found the sub sequence mom first we need to break because we need to print the first sub sequence that was uttered first.

=======================================================================

Snake Procession

Problem Code: SNAKPROC

Solution:


#include <stdio.h>
#include <string.h>
int main(void) {
int t;
scanf("%d",&t);
while(t--)
{
    int n,i,j=0,f=0,k;
    scanf("%d",&n);
    char st[n+1],temp[n+1];
    scanf("%s",st);
    int l =strlen(st);
    for(i=0;i<l;i++)
        if(st[i] !='.')
            temp[j++]=st[i];
    if(j == 0)
        f=1;
    else if (j%2 == 0)
        for(k=0;k+1<j;k=k+2)
            if(temp[k] == 'H' && temp[k+1] == 'T')
                f=1;
            else
            {
                f=0;
                break;
            }
   if(f == 1)
    printf("Valid\n");
   else
    printf("Invalid\n");
 
}
return 0;
}

in the above program never write  st[k+1] !='\0' and always use string length and compare whether index+1 exceeds string length or not.
Here as the index, k is not incremented by 1 but by 2 and hence we are not supposed to use
st[k+1]!='\0'

No comments:

Post a Comment