I am trying to solve the following via recursion: In a phone we have each digit mapped to a number.
Example:
1 2(ABC) 3(DEF)
4(GHI) 5(JKL) 6(MNO)
7(PRS) 8(TUV) 9(XYZ)
* 0 #
I need to print out all the possible sequences of a phone number (example: 637-8687
).
I did the following that seems to solve it:
static Map<String, String> digits;
static{
digits = new HashMap<String, String>();
digits.put("2", "ABC");
digits.put("3", "DEF");
digits.put("4", "GHI");
digits.put("5", "JKL");
digits.put("6", "MNO");
digits.put("7", "PRS");
digits.put("8", "TUV");
digits.put("9", "XYZ");
}
public static void printSequences(String phoneNumber, Map<String, String> associations){
if(phoneNumber == null || phoneNumber.isEmpty()){
throw new IllegalArgumentException();
}
if(associations == null || associations.isEmpty()){
throw new IllegalArgumentException();
}
String[] letters = new String[phoneNumber.length()];
for(int i = 0; i < phoneNumber.length(); i++){
String seq = associations.get(phoneNumber.charAt(i) + "");
if(seq == null)continue;
letters[i] = seq;
}
printSequences(letters, 0, letters.length, "");
}
private static void printSequences(String[] letters, int start, int end, String prefix) {
if(start == end){
System.out.println(prefix);
return;
}
String sequence = letters[start];
if(sequence == null)
return;
for(int i = 0; i < sequence.length(); i++){
printSequences(letters, start + 1, end, prefix + sequence.charAt(i));
}
}
The String[] letters
has all the relevant digits (extracted from a Map
). In this case it is [MNO, DEF, PRS, TUV, MNO, TUV, PRS]
for phone 6378687
.
This code seems to work but does not for 637-8687
. For 637-8687
it actually prints nothing at all!
I am trying to practice recursion, so could you please help me out with this one? Also, is recursion actually the best approach on such a problem?
Q
on7
andW
on9
! \$\endgroup\$