diff options
| author | Paulo Custodio <pauloscustodio@gmail.com> | 2021-06-19 21:14:03 +0100 |
|---|---|---|
| committer | Paulo Custodio <pauloscustodio@gmail.com> | 2021-06-19 21:14:03 +0100 |
| commit | d5d9907992a2d62978c0b511d0afb18b4013cf8d (patch) | |
| tree | 21f1feefc59dd3281151b60e8e4b5acacafbd2f2 /challenge-005/paulo-custodio/cpp/ch-2.cpp | |
| parent | eda544efa917e0b554c55cdcc155c19f836ebb4b (diff) | |
| download | perlweeklychallenge-club-d5d9907992a2d62978c0b511d0afb18b4013cf8d.tar.gz perlweeklychallenge-club-d5d9907992a2d62978c0b511d0afb18b4013cf8d.tar.bz2 perlweeklychallenge-club-d5d9907992a2d62978c0b511d0afb18b4013cf8d.zip | |
Add C and C++ solution to challenge 005
Diffstat (limited to 'challenge-005/paulo-custodio/cpp/ch-2.cpp')
| -rw-r--r-- | challenge-005/paulo-custodio/cpp/ch-2.cpp | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/challenge-005/paulo-custodio/cpp/ch-2.cpp b/challenge-005/paulo-custodio/cpp/ch-2.cpp new file mode 100644 index 0000000000..7741b01977 --- /dev/null +++ b/challenge-005/paulo-custodio/cpp/ch-2.cpp @@ -0,0 +1,66 @@ +/* +Challenge 005 + +Challenge #2 +Write a program to find the sequence of characters that has the most anagrams. + +create a hash of all words in dictionary where key is sorted list of letters +therefore two anagrams have the same key +*/ + +#include <algorithm> +#include <cctype> +#include <fstream> +#include <iostream> +#include <map> +#include <string> +using namespace std; + +map<string, int> anagrams; + +void strtolower(string& str) { + for (size_t i = 0; i < str.size(); i++) + str[i] = tolower(str[i]); +} + +void word_key(string& key, const string& word) { + key = word; + sort(key.begin(), key.end()); +} + +int main() { + int max_anagrams = 0; + string key, line; + + ifstream ifs("words.txt"); + if (!ifs.is_open()) return EXIT_FAILURE; + + // collect anagram keys and count occurrences + while (getline(ifs, line)) { + strtolower(line); + word_key(key, line); + + auto found = anagrams.find(key); + if (found == anagrams.end()) { + anagrams[key] = 1; + + if (max_anagrams < 1) + max_anagrams = 1; + } + else { + found->second++; + + if (max_anagrams < found->second) + max_anagrams = found->second; + } + } + + // list anagrams + cout << "Maximum of " << max_anagrams << " anagrams" << endl; + for (auto& it : anagrams) { + if (it.second == max_anagrams) + cout << it.first << endl; + } + + return EXIT_SUCCESS; +} |
