· 8 years ago · May 25, 2018, 08:04 AM
1#include "HashTable.h"
2#include "WordEntry.h"
3#include <cstdlib>
4#include <list>
5
6/* HashTable constructor
7* input s is the size of the array
8* set s to be size
9* initialize array of lists of WordEntry
10*/
11HashTable::HashTable (int s) : size(s){
12 hashTable = new list<WordEntry>[s];
13}
14
15/* computeHash
16* return an integer based on the input string
17* used for index into the array in hash table
18* be sure to use the size of the array to
19* ensure array index doesn't go out of bounds
20*/
21// parameter s will be a word
22int HashTable::computeHash(const string &s) {
23
24 int stringSize = s.size();
25 // string newS = s;
26 // char c = newS.at(0);
27 // int num = atoi(c);
28 return (s.size()) % size;
29}
30
31
32
33/* put
34* input: string word and int score to be inserted
35* First, look to see if word already exists in hash table
36* if so, addNewAppearence with the score to the WordEntry
37* if not, create a new Entry and push it on the list at the
38* appropriate array index
39*/
40void HashTable::put(const string &s, int score) {
41 if(contains(s)){
42 // means string is in hash
43
44 for(
45 list<WordEntry>:: iterator i = hashTable[computeHash(s)].begin();
46 i != hashTable[computeHash(s)].end();
47 ++i){
48 if (i->getWord() == s) {
49 i->addNewAppearance(score);
50 return;
51 }
52 }
53
54 }else{
55 WordEntry temp(s, score);
56 hashTable[computeHash(s)].push_back(temp);
57 return;
58 }
59}
60
61/* getAverage
62* input: string word
63* output: the result of a call to getAverage()
64* from the WordEntry
65* Must first find the WordEntry in the hash table
66* then return the average
67* If not found, return the value 2.0 (neutral result)
68*/
69
70double HashTable::getAverage(const string &s) {
71 if (!contains(s)) {
72 return 2.0;
73 } else {
74 for (list<WordEntry>::iterator i = hashTable[computeHash(s)].begin();
75 i != hashTable[computeHash(s)].end(); ++i) {
76 if (i->getWord() == s){
77 return i->getAverage();
78 }
79 }
80 }
81
82}
83
84/* contains
85* input: string word
86* output: true if word is in the hash table
87* false if word is not in the hash table
88*/
89bool HashTable::contains(const string &s) {
90 int num = computeHash(s);
91
92 for (list<WordEntry>::iterator i = hashTable[num].begin(); i != hashTable[num].end(); ++i) {
93 if (i->getWord() == s){
94 return true;
95 }
96 }
97 return false;
98}