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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
void histogram(const int MaxWords, istream& input, ostream& output)
{
int nWords = MaxWords;
string *words = new string[nWords];
//* Declare an array of strings to hold all words
int *wordCount = new int[nWords];
//* and an array of int to hold the number of times each word
//* encountered.
// Read the words from the input and count them
string word;
while (input >> word)
{
insertionSort(words, nWords);
for(int i=0;i < nWords; i++){
reduceWords(words[i]);
if (binarySearch(words, nWords, word) == true)
wordCount[i]= wordCount[i]+1;
else
if (i < nWords)
{
addInOrder(words, nWords, word);
wordCount[i] = wordCount[i]+1;
}
else
if (i > MaxWords)
{
cerr<<"Input file contains more than "<<MaxWords<<" words.";
exit(1);
}
}
//* Reduce the word and, if any characters are left
//* check to see if the word in already in our array
//* If so, add one to that word's counter
//* If not, is there room to add it to the array?
//** If so, add the word and a counter to the arrays, setting the
//** counter to 1.
//** If not, print the error message and abort the program [exit(1);]
}
for (int i = 0;i < MaxWords; i++)
cout << words[i] << "," << wordCount[i]<<endl;
//* Print all the words found, with their counts, in .csv format.
delete [] words;
delete [] wordCount;
//* Clean up the arrays we created
}
template <typename T>
int addInOrder (T* array, int& size, T value)
{
// Make room for the insertion
int toBeMoved = size - 1;
while (toBeMoved >= 0 && value < array[toBeMoved]) {
array[toBeMoved+1] = array[toBeMoved];
--toBeMoved;
}
template <typename T>
int addInOrder (T* array, int& size, T value)
{
// Make room for the insertion
int toBeMoved = size - 1;
while (toBeMoved >= 0 && value < array[toBeMoved]) {
array[toBeMoved+1] = array[toBeMoved];
--toBeMoved;
}
// Insert the new value
array[toBeMoved+1] = value;
++size;
return toBeMoved+1;
}
|