-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChaining.java
57 lines (48 loc) · 1.7 KB
/
Chaining.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
package A1;
import java.util.*;
import static A1.main.*;
public class Chaining {
public int m; // number of SLOTS AVAILABLE
public int A; // the default random number
int w;
int r;
public ArrayList<ArrayList<Integer>> Table;
//Constructor for the class. sets up the data structure for you
protected Chaining(int w, int seed) {
this.w = w;
this.r = (int) (w - 1) / 2 + 1;
this.m = power2(r);
this.Table = new ArrayList<ArrayList<Integer>>(m); //creating the table with m primary slots
for (int i = 0; i < m; i++) {
Table.add(new ArrayList<Integer>()); //creating reference to subordinate arraylists in each table slot
}
this.A = generateRandom((int) power2(w - 1), (int) power2(w), seed);
}
/**
* Implements the hash function h(k)
*/
public int chain(int key) {
//ADD YOUR CODE HERE (change return statement)
int hashValue = 0;
return hashValue = ((this.A*key) % (int)(Math.pow(2, this.w))) >> (w-r);
}
/**
* Checks if slot n is empty
*/
public boolean isSlotEmpty(int hashValue) {
return Table.get(hashValue).size() == 0;
}
/**
* Inserts key k into hash table. Returns the number of collisions
* encountered
*/
public int insertKey(int key) {
//ADD YOUR CODE HERE (chane return statement)
int hashValue = this.chain(key);
int col = 0;
//number of collisions is equal to the number of elements in the given subordinate arraylist
col = Table.get(hashValue).size();
Table.get(hashValue).add(key);
return col;
}
}