How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2076
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

相关标签:
30条回答
  • 2020-12-22 18:36

    An R solution using nested loops:

    # Create phone pad
    two <- c("A", "B", "C")
    three <- c("D", "E", "F")
    four <- c("G", "H", "I")
    five <- c("J", "K", "L")
    six <- c("M", "N", "O", "P")
    seven <- c("Q", "R", "S")
    eight <- c("T", "U", "V")
    nine <- c("W", "X", "Y", "Z")
    
    # Choose three numbers
    number_1 <- two
    number_2 <- three
    number_3 <- six
    
    # create an object to save the combinations to
    combinations <- NULL
    
    # Loop through the letters in number_1
    for(i in number_1){
    
        # Loop through the letters in number_2
        for(j in number_2){
    
            # Loop through the letters in number_3
            for(k in number_3){
    
                    # Add each of the letters to the combinations object
                    combinations <- c(combinations, paste0(i, j, k)) 
    
            }
    
        }
    
    }
    
    # Print all of the possible combinations
    combinations
    

    I posted another, more bizarre R solution using more loops and sampling on my blog.

    0 讨论(0)
  • 2020-12-22 18:37

    In numeric keyboards, texts and numbers are placed on the same key. For example 2 has “ABC” if we wanted to write anything starting with ‘A’ we need to type key 2 once. If we wanted to type ‘B’, press key 2 twice and thrice for typing ‘C’. below is picture of such keypad.

    keypad http://d2o58evtke57tz.cloudfront.net/wp-content/uploads/phoneKeyboard.png

    Given a keypad as shown in diagram, and a n digit number, list all words which are possible by pressing these numbers.

    For example if input number is 234, possible words which can be formed are (Alphabetical order): adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi

    Let’s do some calculations first. How many words are possible with seven digits with each digit representing n letters? For first digit we have at most four choices, and for each choice for first letter, we have at most four choices for second digit and so on. So it’s simple maths it will be O(4^n). Since keys 0 and 1 don’t have any corresponding alphabet and many characters have 3 characters, 4^n would be the upper bound of number of words and not the minimum words.

    Now let’s do some examples.

    For number above 234. Do you see any pattern? Yes, we notice that the last character always either G,H or I and whenever it resets its value from I to G, the digit at the left of it gets changed. Similarly whenever the second last alphabet resets its value, the third last alphabet gets changes and so on. First character resets only once when we have generated all words. This can be looked from other end also. That is to say whenever character at position i changes, character at position i+1 goes through all possible characters and it creates ripple effect till we reach at end. Since 0 and 1 don’t have any characters associated with them. we should break as there will no iteration for these digits.

    Let’s take the second approach as it will be easy to implement it using recursion. We go till the end and come back one by one. Perfect condition for recursion. let’s search for base case. When we reach at the last character, we print the word with all possible characters for last digit and return. Simple base case.When we reach at the last character, we print the word with all possible characters for last digit and return. Simple base case.

    Following is C implementation of recursive approach to print all possible word corresponding to a n digit input number. Note that input number is represented as an array to simplify the code.

    #include <stdio.h>
    #include <string.h>
    
    // hashTable[i] stores all characters that correspond to digit i in phone
    const char hashTable[10][5] = {"", "", "abc", "def", "ghi", "jkl",
                               "mno", "pqrs", "tuv", "wxyz"};
    
    // A recursive function to print all possible words that can be obtained
    // by input number[] of size n.  The output words are one by one stored
    // in output[]
    void  printWordsUtil(int number[], int curr_digit, char output[], int n)
    {
        // Base case, if current output word is prepared
    int i;
    if (curr_digit == n)
    {
        printf("%s ", output);
        return ;
    }
    
    // Try all 3 possible characters for current digir in number[]
    // and recur for remaining digits
    for (i=0; i<strlen(hashTable[number[curr_digit]]); i++)
    {
        output[curr_digit] = hashTable[number[curr_digit]][i];
        printWordsUtil(number, curr_digit+1, output, n);
        if (number[curr_digit] == 0 || number[curr_digit] == 1)
            return;
    }
    }
    
    // A wrapper over printWordsUtil().  It creates an output array and
    // calls printWordsUtil()
    void printWords(int number[], int n)
    {
    char result[n+1];
    result[n] ='\0';
    printWordsUtil(number, 0, result, n);
    }
    
    //Driver program
    int main(void)
    {
    int number[] = {2, 3, 4};
    int n = sizeof(number)/sizeof(number[0]);
    printWords(number, n);
    return 0;
    }
    

    Output:

    adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
    

    Time Complexity:

    Time complexity of above code is O(4^n) where n is number of digits in input number.

    References:

    http://www.flipkart.com/programming-interviews-exposed-secrets-landing-your-next-job-3rd/p/itmdxghumef3sdjn?pid=9788126539116&affid=sandeepgfg

    0 讨论(0)
  • 2020-12-22 18:37
    #include <sstream>
    #include <map>
    #include <vector>
    
    map< int, string> keyMap;
    
    void MakeCombinations( string first, string joinThis , vector<string>& eachResult )
    {
        if( !first.size() )
            return;
    
        int length = joinThis.length();
        vector<string> result;
    
        while( length )
        {
            string each;
            char firstCharacter = first.at(0);
            each =  firstCharacter;
            each += joinThis[length -1];
            length--;
    
            result.push_back(each);     
        }
    
        first = first.substr(1);
    
        vector<string>::iterator begin = result.begin();    
        vector<string>::iterator end = result.end();
        while( begin != end)
        {
            eachResult.push_back( *begin);
            begin++;
        }
    
        return MakeCombinations( first, joinThis, eachResult);
    }
    
    
    void ProduceCombinations( int inNumber, vector<string>& result)
    {
        vector<string> inputUnits;
    
        int number = inNumber;
        while( number )
        {
            int lastdigit ;
    
            lastdigit = number % 10;
            number = number/10;
            inputUnits.push_back( keyMap[lastdigit]);
        }
    
        if( inputUnits.size() == 2)
        {
            MakeCombinations(inputUnits[0], inputUnits[1], result);
        }
        else if ( inputUnits.size() > 2 )
        {
            MakeCombinations( inputUnits[0] , inputUnits[1], result);
    
            vector<string>::iterator begin = inputUnits.begin();    
            vector<string>::iterator end = inputUnits.end();
    
            begin += 2;
            while(  begin != end )
            {
                vector<string> intermediate = result;
                vector<string>::iterator ibegin = intermediate.begin(); 
                vector<string>::iterator iend = intermediate.end(); 
    
                while( ibegin != iend)
                {
                    MakeCombinations( *ibegin , *begin, result);
                    //resultbegin =  
                    ibegin++; 
                }
                begin++;            
            }
        }
        else
        {
    
        }
    
        return;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        keyMap[1] = "";
        keyMap[2] = "abc";
        keyMap[3] = "def";
        keyMap[4] = "ghi";
        keyMap[5] = "jkl";
        keyMap[6] = "mno";
        keyMap[7] = "pqrs";
        keyMap[8] = "tuv";
        keyMap[9] = "wxyz";
        keyMap[0] = "";
    
        string  inputStr;
        getline(cin, inputStr);
    
        int number = 0;
    
        int length = inputStr.length();
    
        int tens = 1;
        while( length )
        {
            number += tens*(inputStr[length -1] - '0');
            length--;
            tens *= 10;
        }
    
        vector<string> r;
        ProduceCombinations(number, r);
    
        cout << "[" ;
    
        vector<string>::iterator begin = r.begin(); 
        vector<string>::iterator end = r.end();
    
        while ( begin != end)
        {
            cout << *begin << "," ;
            begin++;
        }
    
        cout << "]" ;
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-22 18:37

    This is a recursive algorithm in C++11.

    #include <iostream>
    #include <array>
    #include <list>
    
    std::array<std::string, 10> pm = {
        "0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
    };
    
    void generate_mnemonic(const std::string& numbers, size_t i, std::string& m,
        std::list<std::string>& mnemonics)
    {
        // Base case
        if (numbers.size() == i) {
            mnemonics.push_back(m);
            return;
        }
    
        for (char c : pm[numbers[i] - '0']) {
            m[i] = c;
            generate_mnemonic(numbers, i + 1, m, mnemonics);
        }
    }
    
    std::list<std::string> phone_number_mnemonics(const std::string& numbers)
    {
        std::list<std::string> mnemonics;
        std::string m(numbers.size(), 0);
        generate_mnemonic(numbers, 0, m, mnemonics);
        return mnemonics;
    }
    
    int main() {
        std::list<std::string> result = phone_number_mnemonics("2276696");
        for (const std::string& s : result) {
            std::cout << s << std::endl;
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-22 18:37
        private List<string> strs = new List<string>();        
        char[] numbersArray;
        private int End = 0;
        private int numberOfStrings;
    
        private void PrintLetters(string numbers)
        {
            this.End = numbers.Length;
            this.numbersArray = numbers.ToCharArray();
            this.PrintAllCombinations(this.GetCharacters(this.numbersArray[0]), string.Empty, 0);
        }
    
        private void PrintAllCombinations(char[] letters, string output, int depth)
        {
            depth++;
            for (int i = 0; i < letters.Length; i++)
            {
                if (depth != this.End)
                {
                    output += letters[i];
                    this.PrintAllCombinations(this.GetCharacters(Convert.ToChar(this.numbersArray[depth])), output, depth);
                    output = output.Substring(0, output.Length - 1);
                }
                else
                {
                    Console.WriteLine(output + letters[i] + (++numberOfStrings));
                }
            }
        }
    
        private char[] GetCharacters(char x)
        {
            char[] arr;
            switch (x)
            {
                case '0': arr = new char[1] { '.' };
                    return arr;
                case '1': arr = new char[1] { '.' };
                    return arr;
                case '2': arr = new char[3] { 'a', 'b', 'c' };
                    return arr;
                case '3': arr = new char[3] { 'd', 'e', 'f' };
                    return arr;
                case '4': arr = new char[3] { 'g', 'h', 'i' };
                    return arr;
                case '5': arr = new char[3] { 'j', 'k', 'l' };
                    return arr;
                case '6': arr = new char[3] { 'm', 'n', 'o' };
                    return arr;
                case '7': arr = new char[4] { 'p', 'q', 'r', 's' };
                    return arr;
                case '8': arr = new char[3] { 't', 'u', 'v' };
                    return arr;
                case '9': arr = new char[4] { 'w', 'x', 'y', 'z' };
                    return arr;
                default: return null;
            }
        }
    
    0 讨论(0)
  • 2020-12-22 18:38
    /**
     * Simple Java implementation without any input/error checking 
     * (expects all digits as input)
     **/
    public class PhoneSpeller
    {
    
        private static final char[][] _letters = new char[][]{
                {'0'},
                {'1'},
                {'A', 'B', 'C'},
                {'D', 'E', 'F'},
                {'G', 'H', 'I'},
                {'J', 'K', 'L'},
                {'M', 'N', 'O'},
                {'P', 'Q', 'R', 'S'},
                {'T', 'U', 'V'},
                {'W', 'X', 'Y', 'Z'}
        };
    
        public static void main(String[] args)
        {
            if (args.length != 1)
            {
                System.out.println("Please run again with your phone number (no dashes)");
                System.exit(0);
            }
            recursive_phoneSpell(args[0], 0, new ArrayList<String>());
    
        }
    
    
        private static void recursive_phoneSpell(String arg, int index, List<String> results)
        {
            if (index == arg.length())
            {
                printResults(results);
                return;
            }
            int num = Integer.parseInt(arg.charAt(index)+"");
    
            if (index==0)
            {
                for (int j = 0; j<_letters[num].length; j++)
                {
                    results.add(_letters[num][j]+"");
                }
                recursive_phoneSpell(arg, index+1, results);
            }
            else
            {
                List<String> combos = new ArrayList<String>();
                for (int j = 0; j<_letters[num].length; j++)
                {
                     for (String result : results)
                     {
                         combos.add(result+_letters[num][j]);
                     }
                }
                recursive_phoneSpell(arg, index+1, combos);
            }
        }
    
        private static void printResults(List<String> results)
        {
            for (String result : results)
            {
                System.out.println(result);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题