Skip to content

Instantly share code, notes, and snippets.

@simpleauthority
Created July 5, 2024 02:49
Show Gist options
  • Save simpleauthority/d8d4b6f931cb577d7bcde38181af0fc8 to your computer and use it in GitHub Desktop.
Save simpleauthority/d8d4b6f931cb577d7bcde38181af0fc8 to your computer and use it in GitHub Desktop.
public class Telephone {
private final String number;
private final Map<String, String[]> digitMap = new HashMap<>();
public Telephone(String number) {
this.number = number;
digitMap.put("2", new String[]{"A", "B", "C"});
digitMap.put("3", new String[]{"D", "E", "F"});
digitMap.put("4", new String[]{"G", "H", "I"});
digitMap.put("5", new String[]{"J", "K", "L"});
digitMap.put("6", new String[]{"M", "N", "O"});
digitMap.put("7", new String[]{"P", "Q", "R", "S"});
digitMap.put("8", new String[]{"T", "U", "V"});
digitMap.put("9", new String[]{"W", "X", "Y", "Z"});
}
public List<String> getPossibilities() {
List<String> phoneWords = new ArrayList<>();
recursePhoneWords(this.number, 0, "", phoneWords);
return phoneWords;
}
public void recursePhoneWords(String number, int position, String currentWord, List<String> currentPhoneWords) {
if (currentWord.length() == number.length()) {
currentPhoneWords.add(currentWord);
return;
}
String currChar = String.valueOf(number.charAt(position));
Integer currInt = asIntOrNull(currChar);
boolean isMappable = digitMap.containsKey(currChar);
if (currInt == null || !isMappable) {
// it is either not an integer, or it is not mappable
// we just keep whatever it is and move along the number
recursePhoneWords(number, position + 1, currentWord + currChar, currentPhoneWords);
return;
}
String[] possibleLetters = digitMap.get(currChar);
recursePhoneWords(number, position + 1, currentWord + possibleLetters[0], currentPhoneWords);
recursePhoneWords(number, position + 1, currentWord + possibleLetters[1], currentPhoneWords);
recursePhoneWords(number, position + 1, currentWord + possibleLetters[2], currentPhoneWords);
if (possibleLetters.length > 3) {
recursePhoneWords(number, position + 1, currentWord + possibleLetters[3], currentPhoneWords);
}
}
private Integer asIntOrNull(String input) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException ignore) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment