-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyRandHash.java
More file actions
54 lines (46 loc) · 1.81 KB
/
Copy pathmyRandHash.java
File metadata and controls
54 lines (46 loc) · 1.81 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
public class myRandHash {
final int SIZE = 128;
HashEntry[] hashTable = new HashEntry[SIZE];
private record HashEntry(String line, int probeCount, int initialIndex) {}
rNumGen randomGenerator = new rNumGen(7); // Assuming this is a class that generates unique random integers
private char safeCharAt(String str, int index) {
if (index >= str.length() || str.charAt(index) == ' ') {
return 0;
}
return str.charAt(index);
}
private int leftCircularShift(int n, int d) {
return (n << d) | (n >>> (32 - d));
}
public void insert(String line) {
int hash = 0;
for (int i = 0; i < line.length(); i++) {
int shifted = leftCircularShift(safeCharAt(line, i), i % 32);
hash = (hash + shifted) % SIZE;
}
int result = Math.abs(hash) % SIZE;
int initialRes = result;
int countProbes = 1;
while (hashTable[result] != null) {
result = (result + randomGenerator.uniqueRandInteger()) % SIZE;
countProbes++;
if (result == initialRes) { // Avoid infinite loops in full hash table scenario
System.out.println("Hash table is full, unable to insert more items.");
return;
}
}
hashTable[result] = new HashEntry(line, countProbes, initialRes);
}
public String getHashVal(int i) {
HashEntry entry = hashTable[i];
return entry != null ? entry.line() : null;
}
public int getProbes(int i) {
HashEntry entry = hashTable[i];
return entry != null ? entry.probeCount() : 0;
}
public int getInit(int i) {
HashEntry entry = hashTable[i];
return entry != null ? entry.initialIndex() : 0;
}
}