|
| 1 | +package com.packt.datastructuresandalg.lesson3.hashtable; |
| 2 | + |
| 3 | +import java.math.BigInteger; |
| 4 | + |
| 5 | +public class UniversalHashing implements HashProvider<Integer> { |
| 6 | + |
| 7 | + private final BigInteger i, j; |
| 8 | + private final long p = 47055833459L; |
| 9 | + |
| 10 | + public UniversalHashing() { |
| 11 | + j = BigInteger.valueOf((long) (Math.random() * p)); |
| 12 | + i = BigInteger.valueOf(1 + (long) (Math.random() * (p - 1L))); |
| 13 | + } |
| 14 | + |
| 15 | + public int hashKey(Integer key, int tableSize) { |
| 16 | + return i.multiply(BigInteger.valueOf(key)).add(j) |
| 17 | + .mod(BigInteger.valueOf(p)) |
| 18 | + .mod(BigInteger.valueOf(tableSize)) |
| 19 | + .intValue(); |
| 20 | + } |
| 21 | + |
| 22 | + public static void main(String[] args) { |
| 23 | + UniversalHashing universalHashing = new UniversalHashing(); |
| 24 | + System.out.println(universalHashing.hashKey(337481990, 1000)); |
| 25 | + System.out.println(universalHashing.hashKey(116241990, 1000)); |
| 26 | + System.out.println(universalHashing.hashKey(983611990, 1000)); |
| 27 | + System.out.println(universalHashing.hashKey(201031990, 1000)); |
| 28 | + |
| 29 | + universalHashing = new UniversalHashing(); |
| 30 | + System.out.println(universalHashing.hashKey(337481990, 1000)); |
| 31 | + System.out.println(universalHashing.hashKey(116241990, 1000)); |
| 32 | + System.out.println(universalHashing.hashKey(983611990, 1000)); |
| 33 | + System.out.println(universalHashing.hashKey(201031990, 1000)); |
| 34 | + } |
| 35 | +} |
0 commit comments