Skip to content

Instantly share code, notes, and snippets.

@jin-x
Last active June 6, 2021 09:48
Show Gist options
  • Save jin-x/977fe28a659585dec08138118a703b36 to your computer and use it in GitHub Desktop.
Save jin-x/977fe28a659585dec08138118a703b36 to your computer and use it in GitHub Desktop.
@jinxonik / UniLecs #268
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::cout;
using std::endl;
using std::string;
using std::vector;
class PhoneDecipher
{
public:
void decipher(const string& digits, vector<string>& result);
private:
void decipher_impl(size_t pos);
string const* m_digits;
string m_current;
vector<string>* m_result;
};
// Make list of strings
void PhoneDecipher::decipher(const string& digits, vector<string>& result)
{
result.clear(); // clear list of resulting string list
if (digits.size() == 0) { return; }
m_digits = &digits; // to reduce stack usage
m_current.resize(digits.size()); // string for local result (no extra strings are required)
m_result = &result; // to reduce stack usage
decipher_impl(0);
}
// Implementation (for internal use)
void PhoneDecipher::decipher_impl(size_t pos)
{
unsigned idx = (*m_digits)[pos];
if (idx) {
idx -= '2';
if (idx <= 7) { // 0 = '2' ... 7 = '9'
char ch = "adgjmptw"[idx]; // get first letter
char ch2 = ch + (idx == 5 || idx == 7 ? 4 : 3); // get last letter + 1
do {
m_current[pos] = ch++; // place letter to local result string
decipher_impl(pos+1); // go to next level
} while(ch < ch2);
} else {
m_current[pos] = '?'; // unknown number
decipher_impl(pos+1); // go to next level
}
} else {
m_result->push_back(m_current); // add local string to resulting string list if (pos >= m_digits->size())
}
}
void show_str_list(const vector<string>& list)
{
cout << '{';
bool first = true;
for (const string& s : list) {
if (!first) { cout << ','; }
cout << " \"" << s << '"';
first = false;
}
cout << " }" << endl;
}
int main()
{
vector<string> list;
PhoneDecipher pd;
pd.decipher("", list);
cout << "\"\":\t";
show_str_list(list);
pd.decipher("2", list);
cout << "\"2\":\t";
show_str_list(list);
pd.decipher("23", list);
cout << "\"23\":\t";
show_str_list(list);
pd.decipher("712x", list);
cout << "\"712x\":\t";
show_str_list(list);
pd.decipher("8645327", list);
cout << "\"8645327\":\t";
cout << "list size = " << list.size() << " elements, ";
if (std::binary_search(list.begin(), list.end(), "unilecs")) {
cout << "\"unilecs\" string is found! ;)";
} else {
cout << "\"unilecs\" string is NOT found! :(";
}
cout << endl;
pd.decipher("123456789753", list);
cout << "\"123456789753\":\t";
cout << "list size = " << list.size() << " elements." << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment