سؤال

I have a puzzle that I solved. I will try to briefly describe it and then ask question.

Map phone numbers to text. For example: 101 -> 101, but 501 -> J01, K01, L01 (AFAIK).

We get 9digit number and need to produce all combination, even those that are not grammaticaly correct.

I created a program that basically grows like a tree. When a number that is not 0 or 1 is found we create a new branch with already translated text + one of possible letters + rest of number.

I solved it by creating a new thread every time new translateable digit is encountered.

Do you think it is a bad practice? Can it be solved better?

Thank you.

هل كانت مفيدة؟

المحلول

Creating a thread for each possibility seems like overkill, what you really want is recursion. Try this:

String [] lookup = { "0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" };

List<String> results = new ArrayList<String>();

void translatePhone(String phoneNumber, int position) {
    int index = Integer.parseInt(phoneNumber.substring(position, position + 1));
    for (int i = 0; i < lookup[index].length; i++) {
        String xlated = phoneNumber.substring(0, position) + lookup[index].charAt(i) + phoneNumber.substring(position + 1);
        if (position + 1 == phoneNumber.length) {
            results.add(xlated);
        } else {
            translatePhone(xlated, position + 1);
        }
    }
}

Call translatePhone(phoneString, 0) to start it off. Once that returns results should have all your results.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top