DEV Community

Discussion on: Daily Challenge #217 - SMS w/ an Old Phone

Collapse
 
vidit1999 profile image
Vidit Sarkar • Edited

C++ solution

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

// returns key bindings for characters as a unordered_map
// Example :
// = ----> ****
// l ----> 555
// - ----> **
// # ----> #-
// . ----> 1
// c ----> 222
// 4 ----> 4-
// etc.
unordered_map<char, string> keyBindings(){
    // all options are in this vector of string
    // last empty string is for character '#'
    vector<string> allOptions = {".,?!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz","'-+="," ",""};

    // make the key bindings for the keys
    unordered_map<char, vector<char>> keyOptions;
    for(int i=0;i<9;i++){
        keyOptions['0'+i+1] = vector<char>(allOptions[i].begin(), allOptions[i].end());
    }
    keyOptions['*'] = vector<char>(allOptions[9].begin(), allOptions[9].end());
    keyOptions['0'] = vector<char>(allOptions[10].begin(), allOptions[10].end());
    keyOptions['#'] = vector<char>(allOptions[11].begin(), allOptions[11].end());

    // this unordered_map maps a character to its key-typing
    // like 'a' -> "2", 'b' -> "22" etc.
    unordered_map<char, string> keyTypings;
    for(auto option : keyOptions){
        for(int i=0;i<option.second.size();i++){
            keyTypings[option.second[i]] = string(i+1,option.first);
        }
        // Add options for numbers like '2' -> "2-", '4' -> "4-"
        keyTypings[option.first] = option.first;
        keyTypings[option.first] += "-";
    }
    return keyTypings;
}


string sendMessage(string message){
    // get the key bindings for characters
    unordered_map<char, string> kb = keyBindings();
    // whether the word is upper case or not, true for upper case
    bool capital = false;
    string res = ""; // answer string

    for(int i=0;i<message.length();i++){
        // if the letter is lower case and capital is true
        // or letter is upper case and capital is false
        // then add a "#" and inverse the capital true to false or false to true
        if((islower(message[i]) && capital) || (isupper(message[i]) && !capital)){
            res += "#";
            capital = !capital;
        }

        // if same character is repeating then add a space
        // like for the case "hi" -> "44 444"
        if(!res.empty() && res[res.length()-1] == kb[tolower(message[i])][0])
            res += " ";

        // add the keybinding for the character's lower case
        res += kb[tolower(message[i])];
    }
    return res;
}

// main function
int main(){
    cout << sendMessage("Def Con 1!") << "\n"; // output -> #3#33 3330#222#666 6601-1111
    cout << sendMessage("hey") << "\n"; // output -> 4433999
    cout << sendMessage("one two three") << "\n"; // output -> 666 6633089666084477733 33
    cout << sendMessage("Hello World!") << "\n"; // output -> #44#33555 5556660#9#66677755531111

    return 0;
}