-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMultiHashTable.java
More file actions
96 lines (88 loc) · 3.16 KB
/
MultiHashTable.java
File metadata and controls
96 lines (88 loc) · 3.16 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
92
93
94
95
96
import java.io.*;
import java.util.*;
public class MultiHashTable {
int[] hashTable;
int[] s;
int numofFlows;
int numOfEntries;
//Constructor for initializing the values for the MultiHashTable
MultiHashTable(int numOfEntries, int numofFlows, int numOfHashes) {
this.numOfEntries = numOfEntries;
this.numofFlows = numofFlows;
hashTable = new int[numOfEntries];
s = new int[numOfHashes];
generateHash(s);
}
// Generate all the Unique Hash values
private void generateHash(int[] s) {
Set<Integer> uniqueHash = new HashSet<>();
for(int i = 0; i < s.length; i++) {
while(true) {
int newHash = random();
if(!uniqueHash.contains(newHash)) {
uniqueHash.add(newHash);
s[i] = newHash;
break;
}
}
}
}
//Generate a random positive number greater than 1
private int random(){
Random random = new Random();
return random.nextInt(Integer.MAX_VALUE - 1) + 1;
}
//Create the hash function
private int[] generateHashFunction(int flowID) {
int[] result = new int[s.length];
for(int i = 0; i < result.length; i++) {
result[i] = flowID ^ s[i];
}
return result;
}
//Fill in the Hash Table with Flow ID's
public int fillHashTable(){
int totalCount = 0;
Set<Integer> uniqueHashTable = new HashSet<>();
for(int i = 0; i < numofFlows; i++) {
int flowID = 0;
// Generate Unique HashID's
while(true) {
flowID = random();
if(!uniqueHashTable.contains(flowID)) {
uniqueHashTable.add(flowID);
break;
}
}
int[] resultHash = generateHashFunction(flowID);
for(int j = 0; j < resultHash.length; j++) {
if(hashTable[resultHash[j] % numOfEntries] == 0) {
hashTable[resultHash[j] % numOfEntries] = flowID;
totalCount++;
break;
}
}
}
return totalCount;
}
public static void main(String[] arg) throws IOException {
MultiHashTable mht = new MultiHashTable(1000,1000,3);
if(arg.length == 3) {
try {
mht = new MultiHashTable(Integer.parseInt(arg[0]),Integer.parseInt(arg[1]),Integer.parseInt(arg[2]));
} catch(NumberFormatException nfe) {
System.out.println("Please provide a valid Input");
}
}
File fout = new File("OutputMultiHashTable.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(Integer.toString(mht.fillHashTable()));
bw.newLine();
for (int i = 0; i < mht.hashTable.length; i++) {
bw.write(Integer.toString(mht.hashTable[i]));
bw.newLine();
}
bw.close();
}
}