-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashing.java
More file actions
115 lines (94 loc) · 2.69 KB
/
Hashing.java
File metadata and controls
115 lines (94 loc) · 2.69 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package general;
import java.util.ArrayList;
// simply change the hash functions in hash or doubleHash
// to adapt to your double hash implementation.
public class Hashing {
static int size = 11;
static int[] arr = new int[size];
static int EMPTY = -88888888;
public static int nbCollision = 0;
public static void main(String[] args) {
//element -99 means empty spot in array
for(int i = 0; i < size; i++)
arr[i] = EMPTY;
/*=== testing double hashing from assignment 3 ===*/
// put(25); put(12); put(42); put(31); put(35); put(39);
// del(31); put(48); del(25); put(18);
// put(29); put(29); put(35);
/*=== testing linear probing ===*/
put(12); put(44); put(13); put(88); put(23); put(94);
put(11); put(39); put(20); put(16); put(5);
print();
System.out.println("Collision nb: " + Hashing.nbCollision);
}
static void put(int nb) {
//arr[hash(nb)] = nb; //double hashing
arr[linearprob(nb)] = nb; //linear probing
}
//remove a nb
static void del(int nb) {
for(int i = 0; i < size; ++i)
if(arr[i] == nb)
arr[i] = EMPTY;
}
//returns index location to add new element
static int hash(int nb) {
//1. mod function
int index = nb % size;
if(arr[index] == EMPTY)
return index;
else
return doubleHash(nb, index);
}
// returns index location to add new element
// should only need to change "(q-nb%q)" and "q"
static int doubleHash(int nb, int firstH) {
int i = 1; // i = 1, 2, ...
int q = 7; //part of the second hash function. (change this as needed)
int index = 0;
boolean go = true; //just to make loop run the first time
//keep hashing till reach an empty spot in array
while(go) {
index = ( (firstH) + i * (q-nb%q) ) % size; //(hashFunc1 + i * hashFunc2) mod N
i++;
nbCollision++;
if(arr[index] == EMPTY) //stop loop, found empty spot
go = false;
}
return index;
}
//linear probing
static int linearprob(int nb) {
int index = (3*nb + 5) % size; //1st hash func
boolean go = true;
if(arr[index] != EMPTY) {
while(go) {
index = (index + 1) % size; //linear probing
nbCollision++;
if(arr[index] == EMPTY)
go = false;
}
}
return index;
}
//quadratic probing
static int quadraticprob(int nb) {
int index = (3*nb + 5) % size; //1st hash func
boolean go = true;
if(arr[index] != EMPTY) {
while(go) {
index = (index^2) % size; //quadratic probing
nbCollision++;
if(arr[index] == EMPTY)
go = false;
}
}
return index;
}
static void print() {
int k=0;
for(int i : arr) {
System.out.println(k++ + " [" + i + "] ");
}
}
}