Thursday, 15 March 2012

Best way to perfectly hash a three letter lowercase String in Java? -



Best way to perfectly hash a three letter lowercase String in Java? -

my current solution uses multi-dimensional array, simpler solution exist? want access hashed objects in o(1) time , want create best utilize of memory space hence need 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); homecoming 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 lower case ascii int[] coord = new int[3]; (int i=0;i<lowercase.length();++i){ int ascii = (int)lowercase.charat(i); int alpha = ascii - 97; // 0-25 coord[i] = alpha; } homecoming coord; } }

you don't need convert string first. if 3 characters lower case, can this.

public static int hashfor(string s) { assert s.length() == 3 && islower(s.charat(0)) && islower(s.charat(1)) && islower(s.charat(2)); homecoming ((s.charat(0) - 'a') * 26 + s.charat(1) - 'a') * 26 + s.charat(2) - 'a'; } // check a-z not lowercase letters. public static boolean islower(char ch) { homecoming ch >= 'a' && ch <= 'z'; }

a more optimise version is

public static int hashfor(string s) { homecoming s.charat(0) * (26 * 26) + s.charat(1) * 26 + s.charat(2) - ('a' * (26*26+26+1)); }

the calculations numbers optimised compiler.

btw using matches() 100x slower else. ;)

you don't need convert lower case if have determined has in lowercase.

java string hash perfect-hash

No comments:

Post a Comment