Showing posts with label Recursion. Show all posts
Showing posts with label Recursion. Show all posts

Saturday, 7 July 2012

To copy the contents of an array A to contents of Array B without using loops and any standard string copy functions.


#include<stdio.h>
int Copy_Array(int A[],int B[], int n,int i)
{
    if(i==n)
        return 0;
    B[i]=A[i];
    Copy_Array(A,B,n,i+1);
return 0;
}

int main()
{
    int A[10],B[10],i,n;
    printf("Enter size : ");
    scanf("%d",&n);
    printf("Enter Array : ");
    for(i=0;i<n;i++)
        scanf("%d",&A[i]);
    printf("\nArray A : ");
    for(i=0;i<n;i++)
        printf("%d ",A[i]);
    Copy_Array(A,B,n,0);
    printf("\nArray B : ");
    for(i=0;i<n;i++)
        printf("%d ",B[i]);
return 0;
}


Let me know your thoughts.

Wednesday, 4 July 2012

WAP to return all anagrams from the array of strings. (all possible permutation of a String)


#include<stdio.h> #include<string.h> int anagram(char S[10],int l,char C[10]) { char D[10]; int j,k,m=strlen(C),i; for(j=0;j<=m;j++) { for(k=m;k>j;k--) D[k]=C[k-1]; D[k]=S[m]; D[m+1]=NULL; for(k=j-1;k>=0;k--) D[k]=C[k]; if((m+1)==l) printf("%s\n",D); else anagram(S,l,D); } return 0;
} int main() { char S[10],C[10]; C[0]=NULL; gets(S); printf("\n"); anagram(S,strlen(S),C); return 0; }

The character 'a' to 'z' are encoded as 1 - 26. Given a string of digits, compute the number of valid decodings of the string. For example, both 'aa' and 'k' can be encoded as '11'. Hence num_valid_encodings('11') = 2.

recursive

#include <stdio.h> #include <string.h> int count_decode(char S[10],int n) { int x1=S[n-1]-'0',x2=S[n-2]-'0',z; if(!n) return 0; else if(n==1) { return 1; } else { z=x2*10+x1; // printf("z=%d ",z); if(z>26) return (count_decode(S,n-1)); else if(n==2) return (count_decode(S,n-1) + count_decode(S,n-2)+1); else return (count_decode(S,n-1) + count_decode(S,n-2)); } } int main() { int i,j,n; char S[10]; gets(S); n=strlen(S); printf("< %d >",count_decode(S,n)); return 0; }