Smart keypad - i

What the problem with base case?

#include<bits/stdc++.h>
using namespace std;

string table[] = { " ", “.+@$”, “abc”, “def”, “ghi”, “jkl” , “mno”, “pqrs” , “tuv”, “wxyz” };

void keypad(char *str,int i,int a,int j){
///base case
if(str[a]==’\0’||str[i]==’\0’||table[i][j]==’\0’||table[i]=="\0"){
return;
}

///recursive case
int x=str[i]-'0';
int y=str[a]-'0';
cout<<table[x][i]<<table[y][j]<<endl;
keypad(str,i,a,j+1);
keypad(str,i+1,a+1,0);

}

int main(){
char str[100];
cin>>str;
keypad(str,0,1,0);
}

Hey @ayusharora17785
There’s a problem in your logic.
What you need to do in the question is, for every element of the given string, you need to look at the corresponding string in the table array given and iterate over the complete length of that string. i.e. for 27 you’ll have to print ap, aq, ar, as, bp, bq, br, bs, cp, cq, cr, cs (i.e. for every element you have to iterate over complete corresponding string in the table array of the number, and do this for every element of the given string, and you need to combine them in all possible ways.)

Your recursive code needs to be like:
int digit = str[i]-‘0’;
for(int k = 0; k < a[digit].length(); k++){
cout << (a[digit][k]);
lPhone(str, i+1, ans);
}

And you need to pass only i index in the function defintion, no other index is required to be passed. Also in the base case you just need to write:
if(str[i] == ‘\0’){
cout << endl;
return;
}
coz you need to print an endl after printing every combination.

1 Like