Letter Phone

Letter Phone


C++ : Generating all possible strings on a letter phone. Implemented in C++11

#include<iostream>
#include<map>
#include<vector>

using namespace std;

class Phone {

    public :

    map<char, string> num_to_char;
    vector<string> possible_strings;

    Phone() {
        num_to_char['0'] = "0";
        num_to_char['1'] = "1";
        num_to_char['2'] = "abc";
        num_to_char['3'] = "def";
        num_to_char['4'] = "ghi";
        num_to_char['5'] = "jkl";
        num_to_char['6'] = "mno";
        num_to_char['7'] = "pqrs";
        num_to_char['8'] = "tuv";
        num_to_char['9'] = "wxyz";
    }

    void Generate(string& current_pressed, string& digit_str) {

        if (current_pressed.size() == digit_str.size()) {
            possible_strings.push_back(current_pressed);
        } else {
            // Go through all the possible letter(s) in the current pressed number
            for (const auto& ch : num_to_char[digit_str[current_pressed.size()]]) {
                current_pressed.push_back(ch);
                Generate(current_pressed, digit_str);
                current_pressed.pop_back();
            }
        }
    }

    vector<string> AllStrings(string digit_str) {
        string current_pressed("");
        possible_strings.clear();
        Generate(current_pressed, digit_str);
        return possible_strings;
    }
};

int main() {

    Phone p;
    vector<string> possible_strings_1 = p.AllStrings("22");
    cout << "Possible strings for code 22 : ";
    for(const auto& str : possible_strings_1)
        cout << str << " ";

    cout << "\nPossible strings for code 1232 : ";
    vector<string> possible_strings_2 = p.AllStrings("1232");
    for(const auto& str : possible_strings_2)
        cout << str << " ";
    return 0;
}

Output

Possible strings for code 22 : aa ab ac ba bb bc ca cb cc
Possible strings for code 1232 : 1ada 1adb 1adc 1aea 1aeb 1aec 1afa 1afb 1afc 1bda 1bdb 1bdc 1bea 1beb 1bec 1bfa 1bfb 1bfc 1cda 1cdb 1cdc 1cea 1ceb 1cec 1cfa 1cfb 1cfc

Copyright © 2020, Algotree.org.
All rights reserved.