Print all possible words from phone digits in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number and we have to print all words that can be formed by pressing those words in an old fashioned mobile keyboard.

We are quite familiar with the QWERTY keyboard style that we use today. But before the invention of QWERTY keypad phones were fitted with keypads with 12 buttons and each button contains words and numbers both. Like they word 6 on the keypad will contain words “MNO” which will be typed by clicking one, twice or thrice the keys.

The keypad looked like this −

12
ABC
3
DEF
4
GHI
5
JKL
6
MNO
7
PQRS
8
TUV
9
WXYZ
*0#

In these keywords also all words are present and the user can type then. So, in this problem, we will be print all possible words that can be generated using the number sequence is given.

Let’s take an example to understand the problem better −

Input: 687
Output: MTP, MTQ, MTR, MTR, MUP, MUQ, MUR, MUS, MVP, MVQ,
MVR, MVR, NTP, NTQ, NTR, NTR, NUP, NUQ, NUR, NUS, NVP, NVQ,
NVR, NVR, OTP, OTQ, OTR, OTR, OUP, OUQ, OUR, OUS, OVP, OVQ,
OVR, OVR.

To solve this problem, let’s see the pattern that is made in the above example. Each button has its own associated characters and we will have to use those while typing. So, for each number, there are at max 4 options(in case of 7 and 9). For this, we can fix on digit and then use then digit and for generated words. This can be done using recursion.

Lets we the program to implement the concept using recursion.

Example

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
const char keypad[10][5] = {"", "", "abc", "def", "ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
void printWords(int number[], int curr_digit, char output[], int n){
   int i;
   if (curr_digit == n){
      cout<<output<<" ";
      return ;
   }
   for (i=0; i<strlen(keypad[number[curr_digit]]); i++){
      output[curr_digit] = keypad[number[curr_digit]][i];
      printWords(number, curr_digit+1, output, n);
      if (number[curr_digit] == 0 || number[curr_digit] == 1)
         return;
   }
}
int main(void){
   int number[] = {6,8,7};
   cout<<"The output character formed is : \n";
   int n = sizeof(number)/sizeof(number[0]);
   char result[n+1];
   result[n] ='\0';
   printWords(number, 0, result, n);
   return 0;
}

Output

The output character formed is −

mtp mtq mtr mts mup muq mur mus mvp mvq mvr mvs ntp ntq ntr nts
nup nuq nur nus nvp nvq nvr nvs otp otq otr ots oup ouq our ous ovp
ovq ovr ovs
raja
Published on 17-Jan-2020 11:23:51
Advertisements