// CS 223A
// 11-29-06
// Demonstrating a hash function for String keys.

package cs223bw;

public class StringHash {

	public static int hashVal(String s, int tableSize)
	// pre: s is not null, tableSize is positive
	// post: returns hash value, f(s), for given table size
	// 0 <= f(s) < tableSize
	{
		int n = s.hashCode()%tableSize;
		// be careful to return a positive number...
		if(n<0)
			n = n+tableSize;
		return n;
	}
	public static void main(String[] args) {
		int N = 7;
		String[] a = new String[N];
		a[0] = "ape";
		a[1] = "bunny";
		a[2] = "cereal";
		a[3] = "Dumbo";
		a[4] = "elephant";
		a[5] = "frantic";
		a[6] = "giraffe";

		for(int i=0; i<N; i++)
			System.out.println("Hash code for " + a[i] + " is " + a[i].hashCode());
		System.out.println();
		System.out.println("If table size is 7... ");
		for(int i=0; i<N; i++)
			System.out.println(a[i] + " hashes to " + hashVal(a[i],7));
		System.out.println();
		System.out.println("If table size is 31... ");
		for(int i=0; i<N; i++)
			System.out.println(a[i] + " hashes to " + hashVal(a[i],31));
		System.out.println();
		System.out.println("If table size is 101... ");
		for(int i=0; i<N; i++)
			System.out.println(a[i] + " hashes to " + hashVal(a[i],101));
	}

}











OUTPUT:

Hash code for ape is 96790
Hash code for bunny is 94099846
Hash code for cereal is -1363909376
Hash code for Dumbo is 66392873
Hash code for elephant is -5491951
Hash code for frantic is -607208459
Hash code for giraffe is 37931892

If table size is 7... 
ape hashes to 1
bunny hashes to 1
cereal hashes to 3
Dumbo hashes to 1
elephant hashes to 4
frantic hashes to 3
giraffe hashes to 5

If table size is 31... 
ape hashes to 8
bunny hashes to 28
cereal hashes to 11
Dumbo hashes to 18
elephant hashes to 9
frantic hashes to 11
giraffe hashes to 13

If table size is 101... 
ape hashes to 32
bunny hashes to 65
cereal hashes to 78
Dumbo hashes to 18
elephant hashes to 25
frantic hashes to 6
giraffe hashes to 29