samedi 17 décembre 2016

Hashtable hash-function implementation in C#

I have array of random numbers from 100-1001 , which i transfer to hash table. Hash function is mod from n ( which is size of array ). The problem is, when im trying to check what is inside hashtable, it shows me different indexes from i have calculated on paper, so im confused if it works correct or not. Also as i was told, size of hash table must be at least 5% bigger than size of array, but i cannot find how to set hashtable size. Where do i have a mistake? Ill have to search value by address using same hash-function after that.

    static void Main()
    {

        int n;

        Console.WriteLine("Please enter array size");
        n = Convert.ToInt32(Console.ReadLine());

        Random rnd = new Random();
        int[] a = new int[n + 4];

        for (int i = 0; i < n; i++)
            Console.Write("{0,4}", a[i] = rnd.Next(100, 1001));    
        // I have deleted code in the middle as there is certain type of search in array which works fine

        // Now putting values to hash table       

        Hashtable Hashtable = new Hashtable();
        int hashcode = n + ((n / 100) * 5);
        int value; 
        int key;
        for (int i = 0; i < n; i++)
        {
            value = a[i];
            key = value % hashcode;

            if (Hashtable[key] == null)
                Hashtable.Add(key, value);
            else
            {
                while (Hashtable[key] != null)
                {
                    if (key == (hashcode - 1))
                        key = 0;
                    else
                        key++;
                }
                Hashtable.Add(key, value);
            }
        }

              Console.WriteLine();
    }




Aucun commentaire:

Enregistrer un commentaire