All combinations of strings that can be used to dial a number in C/C++?


With respect of a given number, display or print all possible combinations of strings that can be implemented to dial the given number in a phone with the help of following pecifications.

  • In the given phone, we can dial,

  • 2 implementing A or B or C,

  • 3 implementing D or E or F,

  • ……………….

  • 8 implementing T or U or V,

  • 9 implementing W or X or Y or Z,

  • 1 implementing only 1

  • 0 implementing 0.

For example if 89, is the given phone number, the program should print

TW,TX,TY,TZ,UW,UX,UY,UZ,VW,VX,VY,VZ

#include <stdio.h>
#include <string.h>
// TableHash[i] stores all characters that correspond to digit i in phone const char TableHash[10][5] =
{"", "", "WXYZ", "TUV", "PQRS", "MNO", "GHI", "GHI", "DEF", "ABC"};
// A recursive function to display or print all possible words that can be obtained by implementing input number1[] of size n1.
The output words are one by one stored in output1[] void UtilWordsPrint(int number1[], int curr_digit1, char output1[], int n1) {
         // In the Base case, if current output word is prepared int i; if (curr_digit1 == n1) {
            printf("%s ",  
            output1); return ;
       }
   // We try all 3 possible characters for current digit in number1[]
   // and recur for remaining digits
   for (i=0; i<strlen(TableHash[number1[curr_digit1]]); i++) {
      output1[curr_digit1] =
      TableHash[number1[curr_digit1]][i];
      UtilWordsPrint(number1, curr_digit1+1, output1, n1);
      if (number1[curr_digit1] == 0 || number1[curr_digit1] == 1)
      return;
   }
}
// A wrapper over UtilWordsPrint(). It is able to create an output1 array and calls UtilWordsPrint() void printWords(int number1[], int n1) {
   char result1[n1+1];
   result1[n1] ='\0';
   UtilWordsPrint(number1, 0, result1, n1);
}
//Driver program int main(void) {
   int number1[] = {2, 3, 4};
   int n1 = sizeof(number1)/sizeof(number1[0]);
    printWords(number1, n1); return 0;
 }

Output

WTP WTQ WTR WTS WUP WUQ WUR WUS WVP WVQ WVR WVS XTP XTQ XTR XTS XUP XUQ XUR XUS XVP XVQ XVR XVS YTP YTQ YTR YTS YUP YUQ YUR YUS YVP YVQ YVR YVS ZTP ZTQ ZTR ZTS ZUP ZUQ ZUR ZUS ZVP ZVQ ZVR ZVS

Time Complexity: Time complexity of above code beO(4n) where n is treated as number of digits in input number.

Updated on: 29-Jan-2020

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements