// CSE143 Au00 Hw1 Sample Solution // HP 9/00 // wordlist.cpp - Implementation of word/frequency operations #include #include using namespace std; #include "wordlist.h" // Set w to empty void make_empty(WordList &w) { w.nWords = 0; } // If word s is in list w, increase its frequency by 1, // otherwise add it to w with a frequency of 1. void count_word(string s, WordList &w) { int loc; // search for s in w loc = 0; while (loc < w.nWords && s != w.entry[loc].word) loc++; // if loc < w.nWords here, we found it, so increase frequency; // otherwise add it to the list if (loc < w.nWords) { w.entry[loc].frequency++; } else { w.entry[loc].word = s; w.entry[loc].frequency = 1; w.nWords++; } } // = location of "largest" word/frequency entry in w.entry[k..nWords-1] // (either largest frequency, or if equal frequencies, first alphabetically // with that frequency), i.e., entry that should move to the front of the list. int front_loc(int k, WordList &w) { int front; // location of "largest" entry in w.entry[k.j] int j; front = k; for (j = k+1; j < w.nWords; j++) { if (w.entry[j].frequency > w.entry[front].frequency || ((w.entry[j].frequency == w.entry[front].frequency) && (w.entry[j].word < w.entry[front].word))) front = j; } return front; } // Sort entries in w in descending order by word frequencies. // If two words have the same frequency, place them in alphabetical order void sort_words(WordList &w) { // selection sort - move largest unsorted item to front int k; int front; for (k = 0; k < w.nWords - 1; k++) { front = front_loc(k, w); // swap entries k and front WordInfo temp = w.entry[k]; w.entry[k] = w.entry[front]; w.entry[front] = temp; } } // Print on cout the first n entries in w, or all entries if n > w.nWords void print_n_words(int n, WordList &w) { if (n > w.nWords) n = w.nWords; for (int k = 0; k < n; k ++) cout << w.entry[k].frequency << '\t' << w.entry[k].word << endl; }