Add mid_square hashing

This commit is contained in:
Kumiho 2018-05-13 13:39:53 +02:00
parent b03f39a8e5
commit 4ff1282433

View File

@ -4,6 +4,7 @@ import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList; import java.util.ArrayList;
import frame.Entry; import frame.Entry;
@ -45,7 +46,7 @@ public class HashTable {
*/ */
public HashTable(int k, String hashFunction, String collisionResolution) { public HashTable(int k, String hashFunction, String collisionResolution) {
this.data = new Entry[k]; this.data = new Entry[k];
this.hashFunction = 0; // TODO this.hashFunction = hashFunction.equals("mid_square") ? 2 : 0; // TODO
this.probingMode = collisionResolution.equals("quadratic_probing") ? 1 : 0; this.probingMode = collisionResolution.equals("quadratic_probing") ? 1 : 0;
this.valueCount = 0; this.valueCount = 0;
this.capacity = k; this.capacity = k;
@ -276,6 +277,8 @@ public class HashTable {
private int getHashAddr(String key) { private int getHashAddr(String key) {
if(this.hashFunction == 0) if(this.hashFunction == 0)
return this.divisionHash(key); return this.divisionHash(key);
else if(this.hashFunction == 2)
return this.midSquareHash(key);
else else
return 0; return 0;
} }
@ -285,6 +288,17 @@ public class HashTable {
return Math.toIntExact(decimal % this.capacity); return Math.toIntExact(decimal % this.capacity);
} }
private int midSquareHash(String value) {
int addrLength = (int) Math.ceil(Math.log10(this.capacity));
System.out.println("AddrLen: "+addrLength);
BigInteger dec = BigInteger.valueOf(decimalRepresentation(value));
BigInteger sqr = dec.pow(2);
String str = sqr.toString();
str = str.substring(str.length() - (9+addrLength), str.length() - 9);
System.out.println(str);
return Integer.parseInt(str) % this.capacity;
}
private int getProbingAddr(int base, int i) { private int getProbingAddr(int base, int i) {
if(this.probingMode == 0) if(this.probingMode == 0)
return (base + i) % this.capacity; return (base + i) % this.capacity;