public ArrayList<String> listMnemonics(String number): (From Thinking Recursivel
ID: 3778320 • Letter: P
Question
public ArrayList<String> listMnemonics(String number):
(From Thinking Recursively by Eric Roberts.) On most telephone keypads the letters of the alphabet are mapped to various digits as shown in the picture below:
In order to make their phone numbers more memorable, service providers like to find numbers that spell outsome word (called a mnemonic) appropriate to their business that makes that phone number easier to remember. For example, the phone number for a recorded time-of-day message in some localities is 637-8687(NERVOUS). Write a method listMnemonics that will generate all possible letter combinations that correspond to a given number, represented as a string of digits. This is a recursive backtracking problem, but you are trying to find all the "solutions", not just one. In fact you are trying to find all possible Strings using the English alphabet, not just Strings that are actual "words".
For example, if you call
ArrayList<String> result = recursiveObject.listMnemonics("623")
your method shall generate and return an ArrayList containing the following 27 possible letter combinationsthat correspond to that prefix:
MAD MBD MCD NAD NBD NCD OAD OBD OCDMAE MBE MCE NAE NBE NCE OAE OBE OCEMAF MBF MCF NAF NBF NCF OAF OBF OCF
Note, the order of the Strings in the ArrayList is unimportant. You will use the following helper method:
public String digitLetters(char ch)
This method returns the letters associated with a given digit.You will find it useful to create a method that does most of the real work:
private void recursiveMnemonics(ArrayList<String> result, StringmnemonicSoFar, String digitsLeft)
The ArrayList named result is used to store completed mnemonics. mnemonicSoFar is the String tha thas been built up so far based on various choices of letters for a digit. Initially it is the empty String. digitsLeft consists of the digits from the original number that have not been used so yet. Initially digitsLeft is the entire phone number. (Or collection of digits.)
To kick off the recursion you would call method recursiveMnemonics from listMnemonics:
ArrayList<String> result = new ArrayList<String>();
recursiveMnemonics(result, "", number); // when starting the mnemonic is the empty string
return result;
Explanation / Answer
import java.io.*;
import java.util.*;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.