Skip to content

Commit 8539068

Browse files
authored
Create smartkeypad2.java
Take as input str, a string. str represents keys pressed on a nokia phone keypad. We are concerned with all possible words that can be written with the pressed keys. Assume the following alphabets on the keys: 1 -> abc , 2 -> def , 3 -> ghi , 4 -> jkl , 5 -> mno , 6 -> pqrs , 7 -> tuv , 8 -> wx , 9 -> yz E.g. “12” can produce following words “ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf” a. Write a recursive function which returns the count of words for a given keypad string. Print the value returned. b.Write a recursive function which prints all possible words for a given keypad string (void is the return type for function). Input Format Single line input containing a single integer. Constraints 1 <= Length of string <= 10^3 Output Format Print all the words in a space separated manner. Also print the count of these numbers in next line. Sample Input 12 Sample Output ad ae af bd be bf cd ce cf 9 Explanation 1 can correspond to 'a' , 'b' or 'c' . 2 can correspond to 'd', 'e' or 'f'. We print all combinations of these
1 parent 6e6e71c commit 8539068

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Recursion/smartkeypad2.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.*;
2+
public class Main {
3+
static int count = 0;
4+
static String[] mapping = { "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wx","yz" };
5+
6+
public static void keypad(String digits, String comb) {
7+
8+
if (digits.length() == 0) {
9+
count++;
10+
System.out.print(comb+" ");
11+
return;
12+
}
13+
char digitPressed = digits.charAt(0);
14+
int index = digitPressed - '0';
15+
16+
String mappedString = mapping[index];
17+
18+
for (int i = 0; i < mappedString.length(); i++) {
19+
20+
String leftString = digits.substring(1);
21+
char choice = mappedString.charAt(i);
22+
keypad(leftString, comb + choice);
23+
}
24+
25+
}
26+
27+
28+
public static void main(String args[]) {
29+
Scanner sc = new Scanner(System.in);
30+
String str = sc.nextLine();
31+
keypad(str,"");
32+
System.out.println();
33+
System.out.println(count);
34+
}
35+
}

0 commit comments

Comments
 (0)