Word Frequencies

16.2 Word Frequencies: Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiple times?

  • Notes:

    • My approach was to scan through the book, and store the words as keys into a hash table. The word itself will hash to the words frequency. Naturally, this is the best approach with multiple queries as a preprocessing step in every subsequent operation would occur in O(1) time.

#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std;

// command line: process each arguement in the arguement_vector[0 - > arguement count]
int main(int arguement_count, char **arguement_vector) 
{
    unordered_map<string, int> myMap;
    ifstream file(arguement_vector[1]);
    string word;

    while (file >> word) {
        // if I want lower case words: <algorithm>
        transform(word.begin(), word.end(), word.begin(), ::tolower);
        auto find = myMap.find(word);
        // not found
        if (find == myMap.end()) {
            myMap.insert({ { word }, { 1 } });
        }
        // found
        else {
            myMap.find(word)->second++;
        }
    }
}

Last updated