Skip to content

Instantly share code, notes, and snippets.

@commander-trashdin
Created September 15, 2020 23:04
Show Gist options
  • Save commander-trashdin/0a51e9899c26fbe31224e33648dc0942 to your computer and use it in GitHub Desktop.
Save commander-trashdin/0a51e9899c26fbe31224e33648dc0942 to your computer and use it in GitHub Desktop.
Interview question.
#include <vector>
#include <string>
#include <unordered_map>
#include <fstream>
#include <utility>
#include <algorithm>
#include <cassert>
#include <string_view>
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 (isalpha(inchar)) {
acc.push_back(tolower(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) && !isalpha(inchar)) {
}
}
return table;
}
void PrintInOrder(const std::unordered_map<std::string, size_t>& frequencies, const std::string& ofilename) {
std::vector<std::pair<size_t, std::string_view>> ordered_pairs;
ordered_pairs.reserve(frequencies.size());
for (auto& [str, freq] : frequencies) {
ordered_pairs.emplace_back(freq, str);
}
std::sort(ordered_pairs.begin(), ordered_pairs.end(),
[](const std::pair<size_t, std::string_view>& fst,
const std::pair<size_t, std::string_view>& snd) {
if (fst.first == snd.first) {
return fst.second < snd.second;
}
return fst.first > snd.first;
});
std::ofstream outfile(ofilename);
assert(outfile.good());
for (auto& [freq, str] : ordered_pairs) {
outfile << freq << ' ' << str << '\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