Question
Mapping
'1' = 'A','B','C'
'2' = 'D','E','F'
...
'9' =
input: 112
output :ouput = [AAD, BBD, CCD, AAE, AAF, BBE, BBF, CCE, CCF]
*/
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Mapping words -- Facebook.
Created Date : 14-01-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <set>
#include <hash_map>
#include <algorithm>
using namespace std;
const vector<char> table[9] =
{
{ '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' }
};
void InitializeMappingTable1(vector<hash_map<char, char>>& mappingTable, set<char>& inputSet)
{
mappingTable.clear();
vector<char> iv(inputSet.begin(), inputSet.end());
for (int i = 0; i < table[iv[0] - '1'].size(); ++i){
hash_map<char, char> um;
um.insert({ iv[0] , table[iv[0] - '1'].at(i) });
mappingTable.push_back(um);
}
for (int i = 1; i < iv.size(); ++i){
vector<hash_map<char, char>> mappingTable1;
mappingTable1.swap(mappingTable);
for (auto mapping : mappingTable1){
for (int j = 0; j < table[iv[i] - '1'].size(); ++j){
hash_map<char, char> um(mapping);
um.insert({ iv[i], table[iv[i] - '1'].at(j) });
mappingTable.push_back(um);
}
}
}
}
void Translate(vector<hash_map<char, char>>& mappingTable, vector<char>& input)
{
for (auto m : mappingTable){
for (auto c : input){
cout << m[c];
}
cout << endl;
}
cout << endl;
}
int main()
{
vector<char> input = { '1', '1', '2' };
set<string> output;
set<char> inputSet(input.begin(), input.end());
vector<hash_map<char, char>> mappingTable;
InitializeMappingTable1(mappingTable, inputSet);
Translate(mappingTable, input);
return 0;
}
Output
AAD
AAE
AAF
BBD
BBE
BBF
CCD
CCE
CCF
Press any key to continue . . .
If you want to see all the mapping combinations, the total is 13122
void InitializeMappingTable0(vector<hash_map<char, char>>& mappingTable, set<char>& inputSet)
{
mappingTable.clear();
for (size_t i = 0; i < table[0].size(); ++i){
hash_map<char, char> um;
um.insert({ '1', table[0].at(i)});
mappingTable.push_back(um);
}
for (int i = 1; i < 9; ++i){
vector<hash_map<char, char>> mappingTable1;
mappingTable1.swap(mappingTable);
for (auto mapping : mappingTable1){
for (int j = 0; j < table[i].size(); ++j){
hash_map<char, char> um(mapping);
um.insert({ (char)(i + '1'), table[i].at(j) });
mappingTable.push_back(um);
}
}
}
}