public void AddShouldThrowExceptionWhenTheSameKeyIsAlreadyPresent()
        {
            var hashtable = new HashTable<string, int>();

            hashtable.Add("gosho", 12);
            hashtable.Add("gosho", 2);
        }
        public void RemoveNullKeyElementTest()
        {
            HashTable<Point, int> pointsCounts = new HashTable<Point, int>();
            pointsCounts.Add(new Point(3, 2), 11);

            pointsCounts.Remove(null);
        }
        private static void Main()
        {
            const int elementsCount = 30000;
            var rand = new Random();
            var beforeHash = GC.GetTotalMemory(true);

            var hashTest = new HashTable<int, int>();
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            for (var i = 0; i < elementsCount; i++)
            {
                var currentNum = rand.Next();
                hashTest.Add(currentNum, currentNum);
                hashTest.Contains(currentNum);
            }

            stopWatch.Stop();
            var afterHash = GC.GetTotalMemory(true);

            Console.WriteLine(
                "The time needed to add {0} items in the HashTalbe was {1}", 
                hashTest.Count, 
                stopWatch.Elapsed);
            Console.WriteLine("Current capacity is {0} items", hashTest.Capacity);
            Console.WriteLine("{0} kb used", (afterHash - beforeHash) / 1024);
        }
        public void AddDuplicateKeyElementsTest()
        {
            HashTable<int, char> alphabet = new HashTable<int, char>();

            alphabet.Add(1, 'A');
            alphabet.Add(1, 'a');
        }
Esempio n. 5
0
        static void Main()
        {
            string input = Console.ReadLine();
            var phonebook = new HashTable<string, string>();

            while (input != "search")
            {
                string[] record = input.Split( new char[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
                phonebook.AddOrReplace(record[0], record[1]);
                input = Console.ReadLine();
            }
            
            input = Console.ReadLine();
            
            while (input != "")
            {
                if (phonebook.ContainsKey(input))
                {
                    Console.WriteLine("{0} -> {1}", input, phonebook[input]);
                }
                else
                {
                    Console.WriteLine("Contact {0} does not exist.", input);
                }

                input = Console.ReadLine();
            }
        }
 public void RemoveShouldReturnTrueIfTheKeyIsFoundAndRemovedFromTheHashTable()
 {
     var testHashTable = new HashTable<int, int>();
     testHashTable.Set(1, 1);
     var removed = testHashTable.Remove(1);
     Assert.AreEqual(true, removed);
 }
Esempio n. 7
0
        public static void Main()
        {
            var table = new HashTable<int, int>();

            table.Add(1, 11);
            table.Add(2, 12);
            table.Add(3, 13);
            table.Add(4, 14);
            table.Add(5, 15);
            table.Add(6, 16);
            table.Add(7, 17);
            table.Add(8, 18);
            //var four = table.Find(4);
            Console.WriteLine();
            Console.WriteLine(table.Count);
            table.Remove(4);
            table.Remove(4);
            Console.WriteLine();
            Console.WriteLine(table.Count);
            Console.WriteLine();
            var secondfour = table.Find(4);
            Console.WriteLine(table.Count);
            Console.WriteLine(secondfour);
            Console.WriteLine(table[1]);
            table[1] = 15;
            Console.WriteLine(table[1]);
            Console.WriteLine(string.Join(", ", table.Keys));
        }
Esempio n. 8
0
        public void Add_OneItem()
        {
            HashTable<string, int> hashTable = new HashTable<string, int>();
            hashTable.Add("Pesho", 6);

            Assert.IsTrue(hashTable.Count == 1);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            var hash = new HashTable<string, int>();

            for (int i = 0; i < 50; i++)
            {
                var name = "Pesho";
                hash.Add(name + i, i);
                Console.WriteLine("Count: " + hash.Count);
                Console.WriteLine("Length: " + hash.Length);

            }

            var result = hash.Find("Pesho4");
            Console.WriteLine(result);
            Console.WriteLine();

            Console.WriteLine("Count is " + hash.Count);
            hash.Remove("Pesho2");
            Console.WriteLine("Now count is " + hash.Count);

            Console.WriteLine("-------");

            foreach (var item in hash)
            {
                Console.WriteLine(item);
            }
        }
 public void RemoveShouldReturnFalseIfTheKeyIsNotFound()
 {
     var testHashTable = new HashTable<int, int>();
     testHashTable.Set(1, 1);
     var removed = testHashTable.Remove(2);
     Assert.AreEqual(false, removed);
 }
 public void IndexerShouldSetThePassedValueToThePassedKey()
 {
     var testHashTable = new HashTable<int, int>();
     testHashTable.Set(1, 1);
     testHashTable[1] = 2;
     Assert.AreEqual(2, testHashTable[1]);
 }
        public void HashTableShouldWorkProperlyWithCollectionValues()
        {
            var testHashTable = new HashTable<int, List<int>>();
            testHashTable.Set(1, new List<int> {1, 2, 3});

            Assert.AreEqual(3, testHashTable[1][2]);
        }
        public void InsertValueByDuplicatedKey_ExpectedException()
        {
            HashTable<int, int> hashTable = new HashTable<int, int>(10);

            hashTable.Add(1, 1);
            hashTable.Add(1, 2);
        }
 public void SetShouldReplaceTheExistingValueWithTheNewOneWhenKeyExists()
 {
     var testHashTable = new HashTable<int, int>();
     testHashTable.Set(1, 1);
     testHashTable.Set(1, 2);
     Assert.AreEqual(2, testHashTable[1]);
 }
        public void ClearShouldEmptyTheTableAndKeepTheCurrentCapacity()
        {
            var table = new HashTable<string, List<int>>();
            for (int i = 0; i < 50; i++)
            {
                table[i.ToString()] = new List<int>();
                for (int j = 0; j < 5; j++)
                {
                    table[i.ToString()].Add(j);
                }

                Assert.IsTrue(table[i.ToString()].Count > 0);
            }

            int finalCapacity = table.Capacity;
            table.Clear();

            Assert.IsTrue(finalCapacity >= 50);
            Assert.AreEqual(finalCapacity, table.Capacity);
            Assert.AreEqual(0, table.Count);

            for (int i = 0; i < 50; i++)
            {
                Assert.IsFalse(table.ContainsKey(i.ToString()));
            }
        }
 private static void PrintClubsPoints(HashTable<string, int> clubsPoints)
 {
     foreach (KeyValuePair<string, int> clubPoints in clubsPoints)
     {
         Console.WriteLine(clubPoints);
     }
 }
Esempio n. 17
0
        private static int HashTable(char[] data)
        {
            int[] diffs = new int[data.Length];
            int diff = 0;

            for(int i = 0; i < data.Length; i++)
            {
                if (LettersAndNumbers.IsNumber(data[i]))
                    diff++;
                else
                    diff--;

                diffs[i] = diff;
            }

            HashTable<int, int> hashTable = new HashTable<int, int>();
            hashTable[0] = -1;
            int max = 0;

            for(int i = 0; i < diffs.Length; i++)
            {
                if (hashTable.Contains(diffs[i]))
                    max = Math.Max(max, i - hashTable[diffs[i]]);
                else
                    hashTable[diffs[i]] = i;
            }

            return max;
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            var contactInfo = new HashTable<string, string>();
            var inSeachMode = false;
            var line = Console.ReadLine();
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    if (line == "search")
                    {
                        var name = Console.ReadLine();
                        var phoneNumber = FindUserInfo(name, contactInfo);
                        Console.WriteLine("{0} -> {1}", name, phoneNumber);

                        inSeachMode = true;
                    }

                    if (!inSeachMode)
                    {
                        ProcessContactInfo(line, contactInfo);
                    }

                    line = Console.ReadLine();
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            HashTable<string, string> phoneBook = new HashTable<string, string>();

            while (true)
            {
                var line = Console.ReadLine();
                if (line == "search")
                {
                    while (true)
                    {
                        line = Console.ReadLine();
                        if (line == "break")
                        {
                            break;
                        }

                        var entry = phoneBook.Find(line);
                        if (entry != null)
                        {
                            Console.WriteLine("{0} -> {1}", entry.Key, entry.Value);
                        }
                        else
                        {
                            Console.WriteLine("Contact {0} does not exist!", line);
                        }
                    }
                }
                else
                {
                    string[] phoneEntries = line.Split(new string[] { DELIMITER }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    phoneBook.Add(phoneEntries[0], phoneEntries[1]);
                }
            }
        }
Esempio n. 20
0
 public void DeleteTest()
 {
     HashTable ht = new HashTable(35);
     ht.AddToHashTable("GUITAR");
     ht.DeleteFromHashTable("GUITAR");
     Assert.IsFalse(ht.Search("GUITAR"));
 }
Esempio n. 21
0
 public void Initialize()
 {
     hashFunction1 = new HashFunction1();
     hashFunction2 = new HashFunction2();
     hashTable1 = new HashTable(5, hashFunction1);
     hashTable2 = new HashTable(5, hashFunction2);
 }
Esempio n. 22
0
        public static void Main()
        {
            var hashtable = new HashTable<int, string>();
            hashtable.Add(5, "five");
            hashtable.Add(3, "tree");
            hashtable.Add(-6, "minus six");
            Console.WriteLine(hashtable.Find(-6));
            Console.WriteLine("All elements");
            foreach (var item in hashtable)
            {
                Console.WriteLine("Key: {0} => Value: {1}", item.Key, item.Value);
            }

            hashtable.Remove(3);
            Console.WriteLine("3 removed from table");
            try
            {
                Console.WriteLine("Searching for 3 in table");
                hashtable.Find(3);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Hash table has {0} elements", hashtable.Count);
        }
        static void Main(string[] args)
        {
            HashTable<int, string> table = new HashTable<int, string>();

            for (int i = 0; i < 17; i++)
            {
                table.Add(i, (i + 1).ToString());
            }

            Console.WriteLine(table[15]);

            table.Clear();

            for (int i = 0; i < 3000; i++)
            {
                table.Add(i, (i + 1).ToString());
            }

            Console.WriteLine(table[1457]);

            //table.Add(1, "test");
            //table.Add(2, "test");
            ////table.Remove(1);
            //Console.WriteLine(table[1]);
        }
Esempio n. 24
0
        static void Main()
        {
            HashTable<string, string> hashTable = new HashTable<string, string>();
            hashTable.Add("1", "aa1");
            hashTable.Add("2", "22a");
            hashTable.Add("3", "wwer");
            hashTable.Add("4", "rrrr");
            hashTable.Add("5", "qqqq");
            hashTable.Add("6", "tttt");

            Console.WriteLine(hashTable.Find("2"));
            Console.WriteLine("Count: {0}", hashTable.Count);

            hashTable.Remove("1");
            Console.WriteLine("Count: {0}", hashTable.Count);
            Console.WriteLine(hashTable["3"]);

            Console.WriteLine("\nKeys: ");
            foreach (var item in hashTable.Keys)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\nIteration with foreach:");
            foreach (var item in hashTable)
            {
                Console.WriteLine("{0}: {1}", item.Key, item.Value);
            }

        }
        static void Main()
        {
            HashTable<string, string> hashTable = new HashTable<string, string>();

            string input = Console.ReadLine();

            while (input != "search")
            {
                string[] parameters = input.Split('-');
                string contact = parameters[0];
                string number = parameters[1];

                hashTable[contact] = number;

                input = Console.ReadLine();
            }

            input = Console.ReadLine();

            while (input != "end")
            {
                if (hashTable.ContainsKey(input))
                {
                    Console.WriteLine("{0} -> {1}", input, hashTable[input]);
                }
                else
                {
                    Console.WriteLine("Contact {0} does not exist", input);
                }

                input = Console.ReadLine();
            }
        }
Esempio n. 26
0
    static void Main()
    {
        HashTable<string, int> hash = new HashTable<string, int>(32);

        hash.Add("Pesho", 6);
        hash.Add("Pesho", 6);
        hash.Add("Pesho", 3);
        hash.Add("Gosho", 9);
        hash.Add("Tosho", 4);
        hash.Add("Viko", 7);
        hash.Add("Viko", 7);
        hash.Add("high 5", 7);
        hash["Johnatan"] = 3333;
        hash["viko"] = 1111111;
        hash.Remove("Tosho");

        foreach (var item in hash)
        {
            Console.WriteLine("{0} -> {1}", item.Key, item.Value);
        }

        hash.Clear();

        foreach (var item in hash)
        {
            Console.WriteLine("{0} -> {1}", item.Key, item.Value);
        }
    }
    /* Task 4: 
     * Implement the data structure "hash table" in a class HashTable<K,T>. 
     * Keep the data in array of lists of key-value pairs (LinkedList<KeyValuePair<K,T>>[]) 
     * with initial capacity of 16. When the hash table load runs over 75%, perform resizing to 2
     * times larger capacity. Implement the following methods and properties: Add(key, value), Find(key)value,
     * Remove( key), Count, Clear(), this[], Keys. Try to make the hash table to support iterating over its elements 
     * with foreach.
     */

    //Few functionalities are missing. If I have time I will add them as well. 

    static void Main(string[] args)
    {
        var hashTable = new HashTable<string, int>();

        for (int i = 0; i < 100; i++)
        {
            hashTable.Add("Entri" + i, i);
        }

        Console.WriteLine(hashTable.Count());
        Console.WriteLine(hashTable.Find("Entri50"));

        for (int i = 50; i < 100; i++)
        {
            hashTable.Remove("Entri" + i);
        }

        //Will throw an exception
        //Console.WriteLine(hashTable.Find("Entri50"));

        var keys = hashTable.Keys();

        foreach (var key in keys)
        {
            Console.WriteLine(key);
        }

        hashTable.Clear();
        Console.WriteLine(hashTable.Count());
    }
        public void AddingByIndexShouldAddCorrectly()
        {
            var table = new HashTable<string, int>();
            table["pesho"] = 2;

            Assert.AreEqual(2, table["pesho"]);
        }
Esempio n. 29
0
    static void Main()
    {
        var grades = new HashTable<string, int>();
        Console.WriteLine("Grades:" + string.Join(",", grades));
        Console.WriteLine("--------------------");

        grades.Add("Peter", 3);
        grades.Add("Maria", 6);
        grades["George"] = 5;
        Console.WriteLine("Grades:" + string.Join(",", grades));
        Console.WriteLine("--------------------");

        grades.AddOrReplace("Peter", 33);
        grades.AddOrReplace("Tanya", 4);
        grades["George"] = 55;
        Console.WriteLine("Grades:" + string.Join(",", grades));
        Console.WriteLine("--------------------");

        Console.WriteLine("Keys: " + string.Join(", ", grades.Keys));
        Console.WriteLine("Values: " + string.Join(", ", grades.Values));
        Console.WriteLine("Count = " + string.Join(", ", grades.Count));
        Console.WriteLine("--------------------");

        grades.Remove("Peter");
        grades.Remove("George");
        grades.Remove("George");
        Console.WriteLine("Grades:" + string.Join(",", grades));
        Console.WriteLine("--------------------");

        Console.WriteLine("ContainsKey[\"Tanya\"] = " + grades.ContainsKey("Tanya"));
        Console.WriteLine("ContainsKey[\"George\"] = " + grades.ContainsKey("George"));
        Console.WriteLine("Grades[\"Tanya\"] = " + grades["Tanya"]);
        Console.WriteLine("--------------------");
    }
Esempio n. 30
0
        public static void Main()
        {
            HashTable<int, string> table = new HashTable<int, string>();

            table.Add(2, "Pesho");
            table.Add(3, "Jhon");
            table.Add(67, "Evlogi");
            table.Add(23, "Jhon");
            table.Add(27, "Pesho");
            table.Add(35, "Jhon");
            table.Add(66, "Evlogi");
            table.Add(11, "Jhon");
            table.Add(32, "Pesho");
            table.Add(19, "Jhon");
            table.Add(12, "Evlogi");
            table.Add(13, "Jhon");
            table.Add(14, "Pesho");
            table.Add(30, "Jhon");
            table.Add(44, "Evlogi");

            foreach (var item in table)
            {
                Console.WriteLine(item.Value);
            }
        }
Esempio n. 31
0
        public void TestHashTableResizing()
        {
            HashTable <int, int> integerTable = new HashTable <int, int>();
            int numberOfElements = 25;

            for (int i = 0; i < numberOfElements; i++)
            {
                integerTable.Add(i, i * 2);
            }

            for (int i = 0; i < numberOfElements; i++)
            {
                Assert.AreEqual(i * 2, integerTable[i], "Incorrectly resizing the array!");
            }

            int actualCount = integerTable.Count;

            Assert.AreEqual(numberOfElements, actualCount, "The table count is incorrectly calculated!");
        }
 /// <summary>
 /// Adds all the common values from a given binary tree and a hash table to a given list.
 /// </summary>
 /// <param name="values">hash table of stringified values to be searched</param>
 /// <param name="root">root of Binary tree to be compared</param>
 /// <param name="result">empty list to hold any found matches</param>
 private static void Intersect(HashTable values, Node root, List <int> result)
 {
     if (root == null)
     {
         return;
     }
     if (root.LeftChild != null)
     {
         Intersect(values, root.LeftChild, result);
     }
     if (root.RightChild != null)
     {
         Intersect(values, root.RightChild, result);
     }
     if (values.Contains(root.Value.ToString()) && !result.Contains(root.Value))
     {
         result.Add(root.Value);
     }
 }
        public void RetrieveTest2()
        {
            // Arrange
            HashTable hashTable = new HashTable();
            var       data1     = new HashTable.HashNode(5, "Андрей");
            var       data2     = new HashTable.HashNode(25, "Сергей");
            var       data3     = new HashTable.HashNode(5, "Олег");

            int count = 2;

            // Act
            hashTable.DoubleHashInsert(data1.Key, data1.Data);
            hashTable.DoubleHashInsert(data2.Key, data2.Data);
            hashTable.DoubleHashInsert(data3.Key, data3.Data);

            // Assert
            Assert.AreEqual(data1.Data, hashTable.Retrieve(data1.Key).Data);
            Assert.AreEqual(count, hashTable.Retrieve(data1.Key).count);
        }
Esempio n. 34
0
        public void HashTableCountWorksCorectWithAddAndRemoveOfElements()
        {
            var hashTable = new HashTable <int, string>();

            var removedElementsCount = 10;
            var expectedCount        = 50 - removedElementsCount;

            for (int i = 0; i < 50; i++)
            {
                hashTable.Add(i, "Test text " + i);
            }

            for (int i = 5; i < removedElementsCount + 5; i++)
            {
                hashTable.Remove(i);
            }

            Assert.AreEqual(expectedCount, hashTable.Count);
        }
Esempio n. 35
0
        public void CanInsertValue()
        {
            //arrange
            HashTable ht = new HashTable();

            //act
            ht.Add("bear", 50);
            ht.Add("act", 5);
            ht.Add("dog", 1);
            ht.Add("pig", 30);
            ht.Add("ball", 75);
            ht.Add("rat", 23);
            ht.Add("man", 99);

            int findValue = ht.Find("bear");

            //assert
            Assert.Equal(50, findValue);
        }
Esempio n. 36
0
        public void Clear_ClearTable()
        {
            HashTable <string, int> hashTable = new HashTable <string, int>();

            hashTable.Add("Pesdfsho1", 6);
            hashTable.Add("Peqeqwsho2", 6);
            hashTable.Add("Peawsho3", 6);
            hashTable.Add("Pesqddho4", 6);
            hashTable.Add("Pwdesho5", 6);
            hashTable.Add("Pescszho6", 6);
            hashTable.Add("Pesaaho7", 6);
            hashTable.Add("Pezxcsho8", 6);
            hashTable.Add("Pesqwdho9", 6);
            hashTable.Add("Pescscho10", 6);

            hashTable.Clear();

            Assert.IsTrue(hashTable.Count == 0);
        }
Esempio n. 37
0
        public void HashTest10000n1000()
        {
            int flag;
            var size = 10000;
            var rnd  = new Random();

            flag = rnd.Next(size);
            var hash = new HashTable(size);

            for (var i = 0; i < size; i++)
            {
                var element = rnd.Next();
                hash.PutPair(i, element);
            }
            for (var i = 0; i < 1000; i++)
            {
                Assert.AreEqual(null, hash.GetValueByKey(rnd.Next(1000) + 10000));
            }
        }
Esempio n. 38
0
    static void WriteData(HashTable table, System.IO.TextWriter writer)
    {
        for (int i = 0; i < table.values.Count(); ++i)
        {
            writer.Write(i + ": ");

            if (table.values[i] != null)
            {
                ListNode <uint> o = table.values[i];

                while (o != null)
                {
                    writer.Write(o.value + " ");
                    o = o.next;
                }
            }
            writer.WriteLine();
        }
    }
Esempio n. 39
0
        public void TestLongestPalindrome()
        {
            var test   = "abccccddaa";
            var result = HashTable.LongestPalindrome(test);

            Assert.AreEqual(9, result);

            test   = "ab";
            result = HashTable.LongestPalindrome(test);
            Assert.AreEqual(1, result);

            test   = "aa";
            result = HashTable.LongestPalindrome(test);
            Assert.AreEqual(2, result);

            test   = "aaa";
            result = HashTable.LongestPalindrome(test);
            Assert.AreEqual(3, result);
        }
Esempio n. 40
0
        public void Find_FindItem()
        {
            HashTable <string, int> hashTable = new HashTable <string, int>();

            hashTable.Add("Pesdfsho1", 6);
            hashTable.Add("Peqeqwsho2", 6);
            hashTable.Add("Peawsho3", 16);
            hashTable.Add("Pesqddho4", 6);
            hashTable.Add("Pwdesho5", 26);
            hashTable.Add("Pescszho6", 6);
            hashTable.Add("Pesaaho7", 56);
            hashTable.Add("Pezxcsho8", 6);
            hashTable.Add("Pesqwdho9", 16);
            hashTable.Add("Pescscho10", 6);

            var actual = hashTable.Find("Pesaaho7");

            Assert.AreEqual(56, actual);
        }
Esempio n. 41
0
        /// <summary>
        /// Checks for first repeated word in a long string
        /// </summary>
        /// <param name="input">The input string</param>
        /// <returns>returns the first repeated word</returns>
        public static string RepeatedWord(string input)
        {
            string[]  temp  = input.ToLower().Split(" ");
            HashTable table = new HashTable();

            foreach (string word in temp)
            {
                if (!table.Contains(word))
                {
                    table.Add(word, word);
                }
                else
                {
                    return(word);
                }
            }

            return("No Repeated Words");
        }
Esempio n. 42
0
        public void TestFindMinWindow()
        {
            var a      = "adobecodebanc";
            var result = HashTable.FindMinWindow(a);

            Assert.AreEqual(7, result);

            a      = "abce";
            result = HashTable.FindMinWindow(a);
            Assert.AreEqual(4, result);

            a      = "aaaa";
            result = HashTable.FindMinWindow(a);
            Assert.AreEqual(1, result);

            a      = "abcabcbb";
            result = HashTable.FindMinWindow(a);
            Assert.AreEqual(3, result);
        }
Esempio n. 43
0
        public void TestHashTableContains()
        {
            HashTable <string, int> hashTable = new HashTable <string, int>(3, 0.9f);

            hashTable.Add("m", 0);
            hashTable.Add("b", 0);
            hashTable.Add("t", 0);
            hashTable.Add("o", 0);
            hashTable.Add("z", 0);
            hashTable.Add("k", 0);
            hashTable.Add("g", 0);
            hashTable.Add("a5", 0);
            hashTable.Add("c", 0);
            hashTable.Add("a2", 0);
            hashTable.Add("a7", 0);
            hashTable.Add("i", 0);
            hashTable.Add("h", 0);

            Assert.IsTrue(hashTable.ContainsKey("m"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("m", 0)));
            Assert.IsTrue(hashTable.ContainsKey("b"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("b", 0)));
            Assert.IsTrue(hashTable.ContainsKey("t"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("t", 0)));
            Assert.IsTrue(hashTable.ContainsKey("o"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("o", 0)));
            Assert.IsTrue(hashTable.ContainsKey("z"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("z", 0)));
            Assert.IsTrue(hashTable.ContainsKey("k"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("k", 0)));
            Assert.IsTrue(hashTable.ContainsKey("g"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("g", 0)));
            Assert.IsTrue(hashTable.ContainsKey("a5"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("a5", 0)));
            Assert.IsTrue(hashTable.ContainsKey("c"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("a2", 0)));
            Assert.IsTrue(hashTable.ContainsKey("a7"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("a7", 0)));
            Assert.IsTrue(hashTable.ContainsKey("i"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("i", 0)));
            Assert.IsTrue(hashTable.ContainsKey("h"));
            Assert.IsTrue(hashTable.Contains(new KeyValuePair <string, int>("h", 0)));
        }
Esempio n. 44
0
        public void TestTryGetValue_Fail()
        {
            HashTable <string, int> hashTable = new HashTable <string, int>();

            hashTable.Add("asd", 10);

            int count = 1000;

            for (int i = 0; i < count; i++)
            {
                hashTable.Add(i.ToString(), i);
            }

            int  value;
            bool found = hashTable.TryGetValue("qwe", out value);

            Assert.AreEqual(false, found);
            Assert.AreEqual(0, value);
        }
Esempio n. 45
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Warcraft.MPQ.MPQ"/> class.
        /// </summary>
        /// <param name="mpqStream">An open stream to data containing an MPQ archive.</param>
        public MPQ([NotNull] Stream mpqStream)
        {
            _archiveReader = new BinaryReader(mpqStream);

            Header = new MPQHeader(_archiveReader.ReadBytes((int)PeekHeaderSize()));

            // Seek to the hash table and load it
            _archiveReader.BaseStream.Position = (long)Header.GetHashTableOffset();

            var encryptedHashTable = _archiveReader.ReadBytes((int)Header.GetHashTableSize());
            var hashTableData      = MPQCrypt.DecryptData(encryptedHashTable, HashTable.TableKey);

            ArchiveHashTable = new HashTable(hashTableData);

            // Seek to the block table and load it
            _archiveReader.BaseStream.Position = (long)Header.GetBlockTableOffset();

            var encryptedBlockTable = _archiveReader.ReadBytes((int)Header.GetBlockTableSize());
            var blockTableData      = MPQCrypt.DecryptData(encryptedBlockTable, BlockTable.TableKey);

            ArchiveBlockTable = new BlockTable(blockTableData);

            if (Header.GetFormat() != MPQFormat.ExtendedV1)
            {
                return;
            }

            // Seek to the extended block table and load it, if necessary
            if (Header.GetExtendedBlockTableOffset() <= 0)
            {
                return;
            }

            _archiveReader.BaseStream.Position = (long)Header.GetExtendedBlockTableOffset();
            var extendedTable = new List <ushort>();

            for (var i = 0; i < Header.GetBlockTableEntryCount(); ++i)
            {
                extendedTable.Add(_archiveReader.ReadUInt16());
            }

            ExtendedBlockTable = extendedTable;
        }
Esempio n. 46
0
        public void TryGet_Succeeds()
        {
            HashTable <string, int> table = new HashTable <string, int>();

            table.Add("100", 100);

            int value;

            Assert.IsTrue(table.TryGetValue("100", out value));
            Assert.AreEqual(100, value, "The returned value was incorrect");

            for (int i = 0; i < 100; i++)
            {
                table.Add(i.ToString(), i);

                Assert.IsTrue(table.TryGetValue("100", out value));
                Assert.AreEqual(100, value, "The returned value was incorrect");
            }
        }
        public void HashTableHashCode()
        {
            var table1 = new HashTable <string, string>()
            {
                { "hello", "world" },
                { "hello", "kitty" }
            };
            var table2 = new HashTable <string, string>()
            {
                { "one", "two" }
            };
            var table3 = new HashTable <string, string>()
            {
                { "one", "two" }
            };

            Assert.AreNotEqual(table1.GetHashCode(), table2.GetHashCode());
            Assert.AreEqual(table2.GetHashCode(), table3.GetHashCode());
        }
        public void AddsOnlyCommons()
        {
            HashTable left = new HashTable();

            left.Add("light", "bright");
            left.Add("nope", "nah");
            left.Add("bad", "evil");
            HashTable right = new HashTable();

            right.Add("nope", "yup");
            right.Add("light", "dark");
            right.Add("good", "evil");
            List <object[]> expected = new List <object[]>();

            expected.Add(new object[] { "bad", "evil", null });
            expected.Add(new object[] { "light", "bright", "dark" });
            expected.Add(new object[] { "nope", "nah", "yup" });
            Assert.Equal(expected, Program.LeftJoin(left, right));
        }
Esempio n. 49
0
        public void KeyPresent_Value()
        {
            //Arrange
            HashTable <string, int> hashTable = new HashTable <string, int>();

            hashTable.Add("key1", 1);
            hashTable.Add("key2", 2);
            hashTable.Add("key3", 3);
            string keyToRemove = "key2";

            //Act
            bool removed = hashTable.Remove(keyToRemove);

            //Assert
            bool valuePresent = hashTable.ContainsKey(keyToRemove);

            Assert.True(removed);
            Assert.False(valuePresent);
        }
        public void HashTableCopyTo()
        {
            var values = new List <KeyValuePair <string, int> >()
            {
                new KeyValuePair <string, int>("one", 1),
                new KeyValuePair <string, int>("two", 2),
                new KeyValuePair <string, int>("three", 3),
            };
            var table = new HashTable <string, int>();

            foreach (var value in values)
            {
                table.Add(value);
            }
            var array = new KeyValuePair <string, int> [3];

            table.CopyTo(array, 0);
            Assert.IsTrue(array.SequenceEqual(values));
        }
        public void CanJoinSingle()
        {
            HashTable synonyms = new HashTable(1);

            synonyms.Add("fond", "enamored");

            HashTable antonyms = new HashTable(1);

            antonyms.Add("fond", "averse");

            string[][] joined = Program.LeftJoin(synonyms, antonyms);

            string[][] expected =
            {
                new string[] { "fond", "enamored", "averse" }
            };

            Assert.Equal(expected, joined);
        }
Esempio n. 52
0
    private void ExpandIfNeeded()
    {
        float loadFactor = (float)(this.Count + 1) / this.Capacity;

        if (loadFactor >= LoadFactor)
        {
            var tempArray = new HashTable <TKey, TValue>(this.Capacity * 2);

            foreach (var kvp in this.elements.Where(e => e != null))
            {
                foreach (var element in kvp)
                {
                    tempArray.Add(element.Key, element.Value);
                }
            }

            this.elements = tempArray.elements;
        }
    }
Esempio n. 53
0
        public void Add_1000_Elements_Grow_ShouldWorkCorrectly()
        {
            // Arrange
            var hashTable = new HashTable <string, int>(1);

            // Act
            var expectedElements = new List <KeyValue <string, int> >();

            for (int i = 0; i < 1000; i++)
            {
                hashTable.Add("key" + i, i);
                expectedElements.Add(new KeyValue <string, int>("key" + i, i));
            }

            // Assert
            var actualElements = hashTable.ToList();

            CollectionAssert.AreEquivalent(expectedElements, actualElements);
        }
Esempio n. 54
0
    public void RemoveMultiple()
    {
        var hashTable = new HashTable <int, int>();

        const int elementsCount = 1000;

        for (int i = 0; i < elementsCount; i++)
        {
            hashTable[i] = i;
        }

        for (int i = 0; i < elementsCount / 2; i++)
        {
            hashTable.Remove(i);
        }

        Assert.AreEqual(elementsCount / 2, hashTable.Count);
        Assert.AreEqual(elementsCount / 2, hashTable.Keys.Count);
    }
Esempio n. 55
0
        public void CanCheckIfContainsCanFindKey()
        {
            //arrange
            HashTable ht = new HashTable();

            //act
            ht.Add("bear", 50);
            ht.Add("act", 5);
            ht.Add("dog", 1);
            ht.Add("pig", 30);
            ht.Add("ball", 75);
            ht.Add("rat", 23);
            ht.Add("man", 99);

            int findValue = ht.Find("bear");

            //assert
            Assert.True(ht.Contains("ball"));
        }
Esempio n. 56
0
        private void RefreshImage()
        {
            this.imgContainerHeight = this.MapContainer.Height * 2;
            this.imgContainerWidth  = this.MapContainer.Width * 2;
            HashTable      tileLayers = this.MapContainer.TileLayerList;
            ScaleTransform zoom       = new ScaleTransform();

            zoom.CenterX = 150;
            zoom.CenterY = 150;
            zoom.ScaleX  = 2;
            zoom.ScaleY  = 2;
            for (int i = 0; i < tileLayers.Length; i++)
            {
                if ((tileLayers.GetItemByIndex(i) as ITile).EnableFillImg &&
                    (tileLayers.GetItemByIndex(i) as UIElement).Visibility == Visibility.Visible)
                {
                    IMap  tmap   = (tileLayers.GetItemByIndex(i) as IMap);
                    Image imgTmp = tmap.DrawToImage();
                    imgTmp.RenderTransform = zoom;
                    this.imgContainer.Children.Add(imgTmp);
                    FrameworkElement ui = (FrameworkElement)(tileLayers.GetItemByIndex(i));
                    tmpCanvasLeft           = Canvas.GetLeft(ui);
                    tmpCanvasTop            = Canvas.GetTop(ui);
                    this.imgContainerWidth  = ui.Width * 2;
                    this.imgContainerHeight = ui.Height * 2;
                }
            }
            HashTable vectorLayers = this.MapContainer.VectorLayerList;

            for (int j = 0; j < vectorLayers.Length; j++)
            {
                if ((vectorLayers.GetItemByIndex(j) as UIElement).Visibility == Visibility.Visible)
                {
                    IMap  vmap   = (vectorLayers.GetItemByIndex(j) as IMap);
                    Image imgTmp = vmap.DrawToImage();
                    imgTmp.RenderTransform = zoom;
                    this.imgContainer.Children.Add(imgTmp);
                    Canvas.SetLeft(imgTmp, -tmpCanvasLeft * 2);
                    Canvas.SetTop(imgTmp, -tmpCanvasTop * 2);
                }
            }
        }
Esempio n. 57
0
        static Nullable <int> HashTableFind(HashTable <string, int> table, string key)
        {
            var arraySize = table.buckets.Length;
            int index     = getIndex(key, arraySize);
            var values    = table.buckets;

            if (values[index] == null)
            {
                return(null);
            }
            else
            {
                if (values[index].Key.Equals(key))
                {
                    return(values[index].Value);
                }
                else
                {
                    // TODO: Ex2.1; potentialIndex = ?
                    var potentialIndex = 0; // PLACEHOLDER: REMOVE AND REPLACE WITH YOUR CODE

                    while (values[potentialIndex] != null)
                    {
                        if (values[potentialIndex].Key.Equals(key))
                        {
                            return(values[potentialIndex].Value);
                        }

                        potentialIndex++;
                        if (potentialIndex >= arraySize)
                        {
                            potentialIndex = 0;
                        }
                        if (potentialIndex == index)
                        {
                            return(null);
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 58
0
        private static void Run()
        {
            HashTable hashTable = new HashTable();

            FillWithDict(hashTable);
            hashTable.ShowTableInfo();
            bool running = true;

            while (running)
            {
                Console.WriteLine($"{Prompts["operations"]}");
                string input = Console.ReadLine();
                string word  = "";

                switch (input)
                {
                case "1":
                    Console.Write($"{Prompts["word"]}");
                    word = Console.ReadLine();
                    hashTable.Add(word);
                    hashTable.ShowTableInfo();
                    break;

                case "2":
                    Console.Write($"{Prompts["word"]}");
                    word = Console.ReadLine();
                    hashTable.Find(word);
                    break;

                case "3":
                    Console.Write($"{Prompts["word"]}");
                    word = Console.ReadLine();
                    hashTable.Delete(word);
                    hashTable.ShowTableInfo();
                    break;

                case "4":
                    running = false;
                    break;
                }
            }
        }
Esempio n. 59
0
        public static void TestHashTableSeekSlot()
        {
            var hashTable = new HashTable(19, 3);
            var slot      = hashTable.SeekSlot("Ro");

            Assert.AreEqual(3, slot);
            slot = hashTable.SeekSlot("R");
            Assert.AreEqual(6, slot);
            slot = hashTable.SeekSlot("Alphanumeric");
            Assert.AreEqual(6, slot);
            slot = hashTable.SeekSlot("Number");
            Assert.AreEqual(9, slot);

            var hashTable2 = new HashTable(3, 1);

            hashTable2.Put("1");
            hashTable2.Put("2");
            hashTable2.Put("3");
            Assert.AreEqual(-1, hashTable2.SeekSlot("4"));
        }
        public void CapacityShouldIncreasePersistently()
        {
            var hashtable    = new HashTable <string, string>();
            var lastCapacity = hashtable.Capacity;
            var counter      = 16;
            var next         = 0;

            while (hashtable.Count < 1024)
            {
                for (int i = 0; i < 1 + (counter * 3) / 4; i++)
                {
                    hashtable.Add((next++).ToString(), "dinozavyr");
                }

                lastCapacity = hashtable.Capacity;
                counter     *= 2;

                Assert.AreEqual(counter, lastCapacity);
            }
        }