Created
September 24, 2020 13:43
-
-
Save commander-trashdin/6e6c06bc3e7559e6ac1ce45d4ab87a9f to your computer and use it in GitHub Desktop.
Slow version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <vector> | |
| #include <string> | |
| #include <unordered_map> | |
| #include <fstream> | |
| #include <utility> | |
| #include <algorithm> | |
| #include <cassert> | |
| #include <string_view> | |
| inline bool is_valid (char c) { | |
| return (65 <= c && c <= 90) || (97 <= c && c <= 122); | |
| } | |
| std::unordered_map<std::string, size_t> Frequencies(const std::string& ifilename) { | |
| std::ifstream infile(ifilename); | |
| assert(infile.good()); | |
| char inchar; | |
| std::string acc; | |
| std::unordered_map<std::string, size_t> table; | |
| infile.get(inchar); | |
| while (!infile.eof()) { | |
| while (is_valid(inchar)) { | |
| if (inchar < 97) { | |
| inchar += 32; | |
| } | |
| acc.push_back(inchar); | |
| infile.get(inchar); | |
| } | |
| auto search = table.find(acc); | |
| if (search != table.end()) { | |
| ++search->second; | |
| } else { | |
| table.emplace(acc, 1); | |
| } | |
| acc.clear(); | |
| while (infile.get(inchar) && !is_valid(inchar)) { | |
| } | |
| } | |
| return table; | |
| } | |
| void PrintInOrder(const std::unordered_map<std::string, size_t>& frequencies, const std::string& ofilename) { | |
| std::vector<const std::pair<const std::string, size_t>*> ordered_pairs; | |
| ordered_pairs.reserve(frequencies.size()); | |
| for (auto& pair : frequencies) { | |
| ordered_pairs.emplace_back(&pair); | |
| } | |
| std::sort(ordered_pairs.begin(), ordered_pairs.end(), | |
| [](const std::pair<const std::string, size_t>* fst, | |
| const std::pair<const std::string, size_t>* snd) { | |
| if (fst->second == snd->second) { | |
| return fst->first < snd->first; | |
| } | |
| return fst->second > snd->second; | |
| }); | |
| std::ofstream outfile(ofilename); | |
| assert(outfile.good()); | |
| for (auto pair : ordered_pairs) { | |
| outfile << pair->second << ' ' << pair->first << '\n'; | |
| } | |
| } | |
| int main(int argc, char *argv[]) { | |
| assert(argc == 3); | |
| PrintInOrder(Frequencies(argv[1]), argv[2]); | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment