-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path04_phone_keypad_problem.cpp
99 lines (75 loc) · 2.25 KB
/
04_phone_keypad_problem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
Topic - Phone Keypad Problem (Recursion)
Generate & print all possible string mapped with the phone keypad number.
Phone Keypad : 0 1 2 3 4 5 6 7 8 9
Characters : "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
Eg: Input : 2
Output : A, B, C
Input : 23
Output : AD, AE, AF, BD, BE, BF, CD, CE, CF
Input : 22
Output : AA, AB, AC, BA, BB, BC, CA, CB, CC
Input : 234
Output : ADG, ADH, ADI, AEG, AEH, AEI, AFG, AFH, AFI, BDG, BDH, BDI, BEG, BEH, BEI, BFG,
BFH, BFI, CDG, CDH, CDI, CEG, CEH, CEI, CFG, CFH, CFI
*/
#include <iostream>
using namespace std;
char keypad[][10] = {"", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};
// function to generate all possible string mapped with the keypad number
void generate_names(char *in, int i, char *out, int j)
{
// base case
if(in[i] == '\0')
{
out[j] = '\0';
cout << out << ", ";
return;
}
// rec case
// extract current digit
int digit = in[i] - '0'; //Eg: '2'-'0' = 2
// for phone keypad digit associated with NULL character
if(digit==0 || digit==1)
{
generate_names(in, i+1, out, j);
}
// for all characters mapped with the phone keypad digit
for(int k=0; keypad[digit][k] != '\0'; k++)
{
out[j] = keypad[digit][k];
// fill the remaining part
generate_names(in, i+1, out, j+1);
}
}
// function to drive code
int main()
{
char in[100];
cout << "Enter phone keypad: ";
cin >> in;
char out[100];
cout << "All String: ";
generate_names(in, 0, out, 0);
cout << endl;
return 0;
}
/*
OUTPUT:
Case 1:
Enter phone keypad: 01
All String: ,
Case 2:
Enter phone keypad: 02
All String: A, B, C,
Case 3:
Enter phone keypad: 666
All String: MMM, MMN, MMO, MNM, MNN, MNO, MOM, MON, MOO, NMM, NMN, NMO, NNM, NNN, NNO, NOM, NON,
NOO, OMM, OMN, OMO, ONM, ONN, ONO, OOM, OON, OOO,
Case 4:
Enter phone keypad: 23
All String: AD, AE, AF, BD, BE, BF, CD, CE, CF,
Case 5:
Enter phone keypad: 123
All String: AD, AE, AF, BD, BE, BF, CD, CE, CF,
*/