namespace Hash
{
class Program
{
static void Main(string[] args)
{
string[] hashTable = new string[10007];//数组长度使用素数
string name;
string[] someName = new string[] { "Wei", "WDQWAS", "QWCQCQ", "WeCQSCi3", "QWC", "SCZ", "VDBC", "XCDF", "XSDXDS", "Wei9" };

        int hashKey;
        for (int i = 0; i < someName .Length; i++)
        {
            name = someName[i];
            hashKey = BatterHashMathf(name, hashTable);
            hashTable[hashKey] = name;
        }
        ShowTable(hashTable);

        Console.WriteLine(InHash("Wei",hashTable));
        Console.WriteLine(GetKey ("Wei",hashTable));

    }

    public static int HashMathf(string s,string [] table)
    {
        int key = 0;
        char[] cname = s.ToCharArray();
        for (int i = 0; i <cname .Length; i++)
        {
            key += (int)cname[i];
        }
        return key % table.GetUpperBound(0);
    }

    //解决冲突的方式
    //桶式散列法
    //开放地址法
    //双重散列法
    public static int BatterHashMathf(string s,string[] arr)
    {
        long key = 0;
        char[] cname = s.ToCharArray();
        for (int i = 0; i < cname.Length; i++)
        {
            key += 37*key+(int)cname[i];
        }
        key = key % arr.GetUpperBound(0);
        if (key < 0)
            key += arr.GetUpperBound(0);
        return (int)key;
    }

    public static void ShowTable(string [] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i]!=null)
                Console.WriteLine(i+":"+arr[i]);
        }
    }

    public static bool InHash(string s,string []arr)
    {
        int hashKey = BatterHashMathf(s, arr);
        if (arr[hashKey].Equals(s))
        {
            return true;
        }else
        {
            return false;
        }
    }

    public static int GetKey(string s,string []arr)
    {
        if (InHash(s, arr))
            return BatterHashMathf(s, arr);
        else
            return -1;
    }

}

}