Find all possible interpretations of an array of digits - cook the code

Sunday, 9 July 2017

Find all possible interpretations of an array of digits


Find all possible interpretations of an array of digits

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.
Examples
Input: {1, 1}
Output: ("aa", 'k") 
[2 interpretations: aa(1, 1), k(11)]

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)]
 
 
#include<iostream>
#include<math.h>
#include<limits.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define ll long long int
#define l long long int
#define repin(i,a,b) for(i=a;i>=b;i--)
#define rep(i,a,b) for(i=a;i<=b;i++)
char alphabet[] =" abcdefghijklmnopqrstuvwxyz";
 
 
 
void printalldecoding(int arr[],int index,char* str,int n){
 
 if(n<=0)
 {
  str[index]='\0';
  cout<<str<<endl;
  return;
 }
 int ind;
 
 
 if(n>=1){
  ind=arr[0];
  str[index]=alphabet[ind];
  printalldecoding(arr+1,index+1,str,n-1);
 } 
 if(n>=2)
 {
  ind=arr[0]*10+arr[1];
  if(ind<=26)
   {
    str[index]=alphabet[ind];
  printalldecoding(arr+2,index+1,str,n-2);
   }
 }
}
int main()
{
      char str[100];
      int arr[] = {1, 2, 2, 1};
      int n= sizeof(arr)/sizeof(arr[0]);
      printalldecoding(arr,0,str,n);
} 


output :-

abba
abu
ava
lba
lu

No comments:

Post a Comment