Description: Design and write a program that reads a text file and counts the nu
ID: 3887185 • Letter: D
Question
Description: Design and write a program that reads a text file and counts the number of times each NON-WHITESPACE character occurs, then computes a single integer (long) value based on the character code and occurrence frequency of each such character. *********************************************************** *********************************************************** Calculation: hash value = sum of products (char_code x char_frequency) *********************************************************** *********************************************************** EXAMPLE: The file simple.dat contains: Fat cat ran slow. But the butterball turkey got stuck on the Thanksgiving table. Program output: (note the FORMATTING--up to 10 per line, spacing) SYMBOL FREQUENCIES: 2. 1B 1F 1T 6a 3b 2c 5e 3g 3h 2i 3k 4l 4n 3o 3r 3s 11t 4u 1v 1w 1y simple.dat HASH VALUE = 7037 .
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
void processFile(char* fileName, map<char, int> &mapOfChars)
{
string line;
ifstream infile (fileName);
if (infile.is_open())
{
while ( getline (infile,line) )
{
for(char c : line)
{
if(c != ' ') // if not space
{
if(mapOfChars.find(c) != mapOfChars.end())
{
mapOfChars[c]++;
}
else
{
mapOfChars.insert(make_pair(c,1));
}
}
}
}
infile.close();
}
else cout << "Unable to open file";
}
long calculateHashValue(map<char, int> &mapOfChars)
{
int hash = 0;
map<char, int>::iterator it = mapOfChars.begin();
while(it != mapOfChars.end())
{
hash += it->first * it->second;
it++;
}
return hash;
}
void printResults(char* filename, map<char, int> &mapOfChars, long hashValue)
{
cout << "SYMBOL FREQUENCIES: ";
int count = 0;
map<char, int>::iterator it = mapOfChars.begin();
while(it != mapOfChars.end())
{
cout << it->second << it->first << " ";
count = (count+1)%10;
if(count == 0)
cout << " ";
it++;
}
cout << " ";
if(count != 0)
cout << " ";
cout << filename << " HASH VALUE = " << hashValue << " ";
}
int main (int argc, char* argv[])
{
if(argc < 2)
{
cout << "Usage: " << argv[0] << " file_name" << std::endl;
return 1;
}
map<char, int> mapOfChars;
processFile(argv[1], mapOfChars);
long hashValue = calculateHashValue(mapOfChars);
printResults(argv[1], mapOfChars, hashValue);
return 0;
}