Consider a coding system for alphabets to integers where ‘a’ is represented as 1, ‘b’ as 2, .. ‘z’ as 26. Given an array of digits (1 to 9) as input, write a function that prints all valid interpretations of input array.
Input: {1, 2, 1} Output: ("aba", "au", "la") [3 interpretations: aba(1,2,1), au(1,21), la(12,1)] Input: {9, 1, 8} Output: {"iah", "ir"} [2 interpretations: iah(9,1,8), ir(9,18)]
The idea here is string can take at-most two paths: 1. Proces single digit 2. Process two digit
#include<stdio.h> char arr[]={' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; void change(int no[],int y, int p , int t ,char *s){ if(p==y){ *s='\0'; printf("%s \n",(s-(t))); } if(p<y){ *s=arr[no[p]]; change(no,y,p+1,t+1,s+1); } if(p+1<y){ int x = 10*no[p]+no[p+1]; if(x<=26){ *s=arr[x]; change(no,y,p+2,t+1,s+1); } } } void main(){ int no[]={1,1,1}; int y = sizeof(no)/sizeof(no[0]); char *s = malloc(sizeof(char)*(y+1)) ; change(no,y,0,0,s); }
No comments:
Post a Comment