-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyHashTable.java
executable file
·140 lines (109 loc) · 2.5 KB
/
MyHashTable.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
public class MyHashTable {
int actualSize;
private int maxSizeOfUnique;
MyLinkedList<WordEntry> list[];
public MyHashTable(int size){
list=new MyLinkedList[size];
actualSize=0;
this.maxSizeOfUnique=size;
for(int i=0;i<this.maxSizeOfUnique;i++)
{
list[i]=new MyLinkedList<WordEntry>();
}
}
public long hashedValue(String key)
{
long hashCode=0;
String str=(String)key;
int i=0;
long factor=1;
while(i<str.length())
{
hashCode+=((int)(str.charAt(i)-'a'))*factor;
factor*=33;
i++;
}
if(( (31*hashCode+39)%maxSizeOfUnique )<0)
{
return -(31*hashCode+39+maxSizeOfUnique)%maxSizeOfUnique;
}
return (31*hashCode+39)%maxSizeOfUnique;
}
public boolean isEmpty()
{
return actualSize==0;
}
public int findValue(String key)
{
int hash=(int)hashedValue(key);
//returns the index in the table for the hashed value of the key
if(list[hash].getSize()==0)
{
return -1;
}
return hash;
}
public WordEntry get(String key)
{
if(findValue(key)==-1)
{
//the key was not found
return null;
}
int index=findValue(key);
Node<WordEntry> it=list[index].head;
//gets the element
while(it.getData()!=null && !it.getData().getWord().equals(key) )
{
it=it.next;
}
if(it.getData()==null)
{
return null;
}
else
{
return it.getData();
}
}
public void put(WordEntry value)
{
int indexToBeAddedAt=(int) hashedValue(value.getWord());
list[indexToBeAddedAt].add(value);
actualSize++;
return;
}
public void addPositionsForWord(WordEntry value) throws LinkedListOutofBoundsException
{
String phrase[]=value.getWord().split(" ");
int i=0;
for (String element : phrase) {
if(element.equals(" ") || element.equals("")) continue;
WordEntry entry=get(element);
if(entry==null)
{
MyLinkedList<Position> l=value.getAllPositionsForThisWord();
WordEntry toPut=new WordEntry(element);
Node<Position> it=l.head;
while(it.getData()!=null)
{
toPut.addPosition(new Position(it.getData().getPageEntry(),it.getData().getWordIndex() + i ));
it=it.next;
}
put(toPut);
i++;
}
else
{
Node<Position> it=value.getAllPositionsForThisWord().head;
while(it.getData()!=null)
{
entry.addPosition(new Position(it.getData().getPageEntry(), it.getData().getWordIndex() +i));
it=it.next;
}
i++;
}
}
return ;
}
}