Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Anagram finder
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//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; }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.6 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0.75 sec
edit mode
|
history
|
discussion
bca abcZ czba fgh gfh abdz uki 2 2 1020325089 108