I wrote up a hash function using the folding method so that anagrams i.e. "ape" &"pea" would hash to the same value. So far most strings I put into it work. But on some occasions I get Number Format Exceptions.
For instance when I pass the string "abalone" with a table size of 109 the exception pops up while the string "abalon" does not.
private static int Hash(String theString,int theTableSize){
//ignore case and remove all non-alphanumeric characters
String temp = theString.toLowerCase();
temp = temp.replaceAll("[^a-zA-Z0-9]", "");
//sort to count # and type of characters when hashing, NOT alphabetical order
char[] arr = temp.toCharArray();
Arrays.sort(arr);
temp = new String(arr);
//Folding Method for Hash
String str_A = temp.substring(0, temp.length()/2);
String str_B = temp.substring(temp.length()/2, temp.length());
System.out.println(str_A + " " + str_B );
return (folding(str_A) + folding(str_B)) % theTableSize;
}
private static int folding(String substring){
int x = 0;
for(int i = 0; i < substring.length(); i++){
int tchar = substring.charAt(i);
String schar = Integer.toString(tchar);
System.out.println(schar);
x = Integer.parseInt(x + schar) ;
x = Math.abs(x);
}
return x;
}
Is there something that I am missing?