package hashing;

/****
 *
 * Class Hashing contains three different string-valued hash functions, as
 * discussed in Lecture Notes Week 5.
 *
 * @author Gene Fisher (gfisher@calpoly.edu)
 * @version 1may01
 */

public class Hashing {

    /**
     * Compute a hash index for the given string by summing the string
     * characters and taking the modulus of the given table size.
     */
    public static int hash1(String key, int tableSize) {
        int hashVal = 0;

        for (int i = 0; i < key.length(); i++) {
            hashVal += key.charAt(i);
        }

        return hashVal % tableSize;
    }

    /**
     * Compute a hash index for the given string by summing the first three
     * string characters with the formula:
     *
     *     char[0] + (27 * char[1]) + (729 * char[2])
     *
     * where 27 is the number of letter in the alphabet + 1 for a blank, and
     * 729 is 27<sup>2</sup>.
     *
     * Return the sum mod the given table size.
     */
    public static int hash2(String key, int tableSize) {
        int hashVal = 0;

        return (key.charAt(0) + (27 * key.charAt(1)) + (729 * key.charAt(2)))
            % tableSize;
    }

    /**
     * Compute a hash index for the given string by summing all of the string
     * characters with the formula:
     *
     *     (37 * char[0]) + (37^2 * char[1]) + ... + (37^(l-1) * char[l])
     *
     * where 37 is an empirically chosen value to provide good distribution and
     * l = key.length().
     *
     * Return the sum mod the given table size.
     */
    public static int hash3(String key, int tableSize) {
        int hashVal = 0;

        for (int i = 0; i < key.length(); i++) {
            hashVal = 37 * hashVal + key.charAt(i);
        }

        hashVal %= tableSize;
        if (hashVal < 0) {
            hashVal += tableSize;
        }

        return hashVal;
    }


}