My current solution uses a multi-dimensional array, does a simpler solution exist? I want to access the hashed objects in O(1) time and want to make best use of memory space hence the need for a perfect hash.
public final class PerfectHash {
private Object[][][] hashtable = new Object[26][26][26];
public void storeObjectAgainst3letterStringKey(Object o, String s){
int[] coord = stringToCoord(s);
hashtable[coord[0]][coord[1]][coord[2]] = o;
}
public Object get(String s){
int[] coord = stringToCoord(s);
return hashtable[coord[0]][coord[1]][coord[2]];
}
private int[] stringToCoord(String s){
if (!s.matches("[a-z][a-z][a-z]")){
throw new IllegalStateException("invalid input, expecting 3 alphabet letters");
}
// 1-26
// 1-26
// 1-26
String lowercase = s.toLowerCase();
// 97-122 integers for lower case ascii
int[] coord = new int[3];
for (int i=0;i<lowercase.length();++i){
int ascii = (int)lowercase.charAt(i);
int alpha = ascii - 97; // 0-25
coord[i] = alpha;
}
return coord;
}
}