aboutsummaryrefslogtreecommitdiff
path: root/challenge-005/paulo-custodio/cpp/ch-2.cpp
blob: 7741b01977ec3ba3ee7b3653876f060c7ef18fa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;
}