-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniversalHashing.java
More file actions
61 lines (43 loc) · 1.52 KB
/
UniversalHashing.java
File metadata and controls
61 lines (43 loc) · 1.52 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
package com.mycompany.algorithm_final_project;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author israkkayumchowdhury
*/
class UniHashing {
private int prime;
private int[] coefficients;
private Random random;
public UniHashing(int prime, int universeSize) {
this.prime = prime;
coefficients = new int[2];
random = new Random();
generateCoefficients(universeSize);
}
private void generateCoefficients(int universeSize) {
coefficients[0] = random.nextInt(prime - 1) + 1;
coefficients[1] = random.nextInt(prime);
if (universeSize > prime)
generateCoefficients(universeSize);
}
public int hash(int key) {
int coefficientA = coefficients[0];
int coefficientB = coefficients[1];
return ((coefficientA * key + coefficientB) % prime) % coefficients.length;
}
}
public class UniversalHashing {
public void main_func(){
Scanner scanner = new Scanner(System.in);
System.out.print(" Enter the size of the universe: ");
int universeSize = scanner.nextInt();
System.out.print(" Enter a prime number greater than the universe size: ");
int prime = scanner.nextInt();
UniHashing hashing = new UniHashing(prime, universeSize);
System.out.print(" Enter a key to hash: ");
int key = scanner.nextInt();
int hashValue = hashing.hash(key);
System.out.println(" Key: " + key + " -> Hash Value: " + hashValue);
}
}