Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Get all anagrams from given words
//Title of this code #include <iostream> #include <vector> #include <map> #include <string> #include <list> #include <set> using namespace std; map<char, int> getCharMap(const string& s) { map<char, int> m; for (int i = 0; i < s.length(); ++i) { if (m.find(s[i]) == m.end()) m[s[i]] = 1; else ++m[s[i]]; } return m; } bool areCharMapEqual(map<char, int>& m1, map<char, int>& m2) { if (m1.size() != m2.size()) return false; auto it1 = m1.begin(); auto it2 = m2.begin(); // the sizes are the same so we don't need further checking while (it1 != m1.end()) { if (it1->first != it2->first || it1->second != it2->second) return false; ++it1; ++it2; } return true; } struct StringAndCharMap { string str; map<char, int> strMap; StringAndCharMap(string s, map<char, int> m): str(s), strMap(m) {} }; void findAnagrams(vector<string>& words) { list<StringAndCharMap> wordsCharMaps; for (int i = 0; i < words.size(); ++i) wordsCharMaps.push_back(StringAndCharMap(words[i], getCharMap(words[i]))); while (!wordsCharMaps.empty()) { map<char, int> curStrMap = wordsCharMaps.begin()->strMap; cout << wordsCharMaps.begin()->str << " "; wordsCharMaps.erase(wordsCharMaps.begin()); auto it = wordsCharMaps.begin(); while (!wordsCharMaps.empty() && it != wordsCharMaps.end()) { if (areCharMapEqual(curStrMap, it->strMap)) { cout << it->str << " "; it = wordsCharMaps.erase(it); } else ++it; } cout << endl; } } int main() { vector<string> words = {"amazon", "zonama", "zomana", "ammazon", "zonnama", "", "anmanoz"}; findAnagrams(words); map<char, int> m1 = getCharMap("zonama"); map<char, int> m2 = getCharMap("zomana"); cout << boolalpha << areCharMapEqual(m1, m2); }
run
|
edit
|
history
|
help
0
cast operator
sdfsdf
PrintShapePointer
Stream3
Peg Grammar AST Parser Computer Language Interpreter
Microsoft - MaxEmployeeAttendence (R repititions - Semi Optimised DP)
Templet
Loop comparison
wealth of banks
Odwrócone podciągi