Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Anagram finder
//Title of this code #include <iostream> #include <cctype> #include <map> #include <list> #include <vector> using namespace std; vector<int> primes; typedef unsigned HashType; // Just working with non repeating letters!!! HashType anagramHash(const string& s) { HashType num = 0; for (unsigned i = 0; i < s.length(); ++i) { int n = static_cast<int>(tolower(s[i]) - 'a'); num += (1 << n); } return num; } HashType anagramHashPrimes(const string& s) { HashType num = 1; for (unsigned i = 0; i < s.length(); ++i) { int n = static_cast<int>(tolower(s[i]) - 'a'); num *= primes[n]; } return num; } void collectAnagrams(list<string>& words, map<int, list<string*>* >& anagrams) { for (auto it = words.begin(); it != words.end(); ++it) { int n = anagramHashPrimes(*it); if (anagrams.find(n) == anagrams.end()) { anagrams[n] = new list<string*>(); anagrams[n]->push_back(&(*it)); } else { anagrams[n]->push_back(&(*it)); } } } void printAnagrams(map<int, list<string*>* >& anagrams) { for (auto it = anagrams.begin(); it != anagrams.end(); ++it) { list<string*> *l = it->second; for (auto lit = l->begin(); lit != l->end(); ++lit) { cout << **lit << " "; } cout << endl; } } bool isPrime(int num) { if (num < 2) return false; if (num == 2) return true; for (int i = 2; i < num; ++i) if (num % i == 0) return false; return true; } void initPrimeVector(vector<int>& p, int size) { int i = 1; int num = 0; while (i <= size) { if (isPrime(num)) { p.push_back(num); ++i; } ++num; } } int main() { initPrimeVector(primes, 26); list<string> words; words.push_back("abcZ"); words.push_back("fgh"); words.push_back("uki"); words.push_back("abdz"); words.push_back("czba"); words.push_back("bca"); words.push_back("gfh"); map<int, list<string*>* > anagrams; collectAnagrams(words, anagrams); printAnagrams(anagrams); cout << endl; // FAIL! cout << anagramHash("aa") << " " << anagramHash("b") << endl; // Can owerflow! cout << anagramHashPrimes("zzzzzzzz") << " " << anagramHashPrimes("abbba") << endl; }
run
|
edit
|
history
|
help
0
Primality test Fermat primality test
PhoneDirectory
cast operator
Anagrams
my template
CPP - Ex 5
Function to m_function
005#
Metodos 2- programa3
ExceptionHandling4