-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoubleHashTable.java
More file actions
91 lines (83 loc) · 2.53 KB
/
DoubleHashTable.java
File metadata and controls
91 lines (83 loc) · 2.53 KB
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
public class DoubleHashTable {
private SpellSimple[] table;
private int capacity;
private int size=0;
private int steps=0;
/**
* Constructor
* @param capacity - Creating hash table in the size of the capacity
*/
public DoubleHashTable(int capacity) {
table = new SpellSimple[capacity];
this.capacity = capacity;
}
/**
* Putting the new spell in the right index, if the index is taking then steps++ doing another loop with index++
* open addressing hash
*/
public boolean put(SpellSimple spell) {
steps = 0; // reset
int index = -1;
if (capacity == size){
return false;
}
while (true){
index++;
int check_in_table = (hash1(spell.getName()) + index * hash2(spell.getName())) % capacity; // hashing
if (index > 0){ // index is taking
steps++;
}
if (table[check_in_table] == null){ // index is npt taking
table[check_in_table] = spell;
size++;
return true;
}
}
}
/**
* We are getting the key and want to return the value which is the magic spell
*/
public String getCastWords(String name) {
int index = 0;
while (index < capacity){ // Going every index
int check_in_table = (hash1(name) + index * hash2(name)) % capacity;
if (table[check_in_table] != null && table[check_in_table].getName() == name){ // equals
return table[check_in_table].getWords();
}
index++;
}
return null;
}
/**
* return size - int
*/
public int getSize() {
return size;
}
/**
* return last steps
*/
public int getLastSteps() { return steps; }
/**
* First hash function
*/
private int hash1(String name) {
int hash =0;
for (int i =0; i < name.length(); i++){
char ch = name.charAt(i);
hash = hash + (31 * (int)ch);
}
return hash % capacity;
}
/**
* Second hash function
*/
private int hash2(String name) {
int hash =0;
for (int i =0; i < name.length(); i++){
char ch = name.charAt(i);
hash = hash + (13 * (int)ch);
}
return 1+hash % (capacity-2);
}
}