Пример #1
0
        public void Add_Unique_Adds()
        {
            HashTable<string, int> table = new HashTable<string, int>();
            List<int> added = new List<int>();

            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual(i, table.Count, "The count was incorrect");

                int value = _rng.Next();
                string key = value.ToString();

                // this ensure we should never throw on Add
                while (table.ContainsKey(key))
                {
                    value = _rng.Next();
                    key = value.ToString();
                }

                table.Add(key, value);
                added.Add(value);
            }

            // now make sure all the keys and values are there
            foreach (int value in added)
            {
                Assert.IsTrue(table.ContainsKey(value.ToString()), "ContainsKey returned false?");
                Assert.IsTrue(table.ContainsValue(value), "ContainsValue returned false?");

                int found = table[value.ToString()];
                Assert.AreEqual(value, found, "The indexed value was incorrect");
            }
        }
        public ICollection<PersonInfo> Find(string name)
        {
            var matches = this.byName.Keys.Where(x => Regex.IsMatch(x, name, RegexOptions.IgnoreCase)).ToList();
            var result = new List<PersonInfo>();

            foreach (var key in matches)
            {
                foreach (var item in this.byName[key])
                {
                    result.Add(item);
                }
            }

            return result;
        }
Пример #3
0
 public static void Main(string[] args)
 {
     Console.WriteLine ("Enter some text");
     var input = Console.ReadLine ();
     var charsDictionary = new HashTable<string, int>(100);
     var charStrings = new List<string>(input.Length);
     foreach(var aChar in input) {
         charStrings.Add(aChar.ToString());
     }
     foreach (var charString in charStrings) {
         if (charsDictionary.ContainsKey (charString)) {
             charsDictionary [charString]++;
         } else {
             charsDictionary [charString] = 1;
         }
     }
     foreach (var charString in charsDictionary) {
         Console.WriteLine ("{0}: {1} time/s", charString.Key, charString.Value);
     }
 }
Пример #4
0
        public void Add_Duplicate_Throws()
        {
            HashTable<string, int> table = new HashTable<string, int>();
            List<int> added = new List<int>();

            for (int i = 0; i < 100; i++)
            {
                Assert.AreEqual(i, table.Count, "The count was incorrect");

                int value = _rng.Next();
                string key = value.ToString();

                // this ensure we should never throw on Add
                while (table.ContainsKey(key))
                {
                    value = _rng.Next();
                    key = value.ToString();
                }

                table.Add(key, value);
                added.Add(value);
            }

            // now make sure each attempt to re-add throws
            foreach (int value in added)
            {
                try
                {
                    table.Add(value.ToString(), value);
                    Assert.Fail("The Add operation should have thrown with the duplicate key");
                }
                catch (ArgumentException)
                {
                    // correct!
                }
            }
        }
        public void Enumerate_Values_Populated()
        {
            HashTable<int, string> table = new HashTable<int, string>();

            List<string> values = new List<string>();
            for (int i = 0; i < 100; i++)
            {
                int value = _rng.Next();
                while (table.ContainsKey(value))
                {
                    value = _rng.Next();
                }

                values.Add(value.ToString());
                table.Add(value, value.ToString());
            }

            foreach (string value in table.Values)
            {
                Assert.IsTrue(values.Remove(value), "The key was missing from the values collection");
            }

            Assert.AreEqual(0, values.Count, "There were left over values in the value collection");
        }
        public void TestGetEnumerator()
        {
            var hashTable = new HashTable<int, int>();

            for (int i = 1; i <= 12; i++)
            {
                hashTable.Add(i, 12 - i + 1);
            }

            var collection = new List<KeyValuePair<int, int>>();

            foreach (var keyValuePair in hashTable)
            {
                var pair = new KeyValuePair<int, int>(keyValuePair.Key, keyValuePair.Value);
                collection.Add(pair);
            }

            Assert.AreEqual(collection.Count, hashTable.Count);

            foreach (var keyValuePair in hashTable)
            {
                Assert.IsTrue(collection.Contains(keyValuePair));
            }
        }
Пример #7
0
        /**
         * Collect bucket statistics
         *
         * @returns {string[]} Array of strings that can be written to a file
         * @api public
         */
        public string[] CollectStatistics()
        {
            List<string> lines = new List<string>();
            List<int> chain = new List<int>();
            Dictionary<int, int> chain_count = new Dictionary<int, int>();

            float chain_avg = 0F;
            float total_length_avg = 0F;
            float total_length = 0F;
            float non_zero_length_buckets = 0F;

            for (int i = 20; i < MAX_BUCKETS; ++i)
            {
                // if overflow is set
                if (this.table[i].overflow != -1)
                {
                    // if overflow is greater than table size, do some weird math stuff.
                    // this accounts for overflows of overflows.
                    // else add to the list normally.
                    if (this.table[i].overflow + 1 >= PRIMARY_TABLE_SIZE)
                    {
                        chain.Add((this.table[i].overflow + 1) - (PRIMARY_TABLE_SIZE - 1));
                    }
                    else
                    {
                        chain.Add(this.table[i].overflow + 1);
                    }
                }
                else
                {
                    //if no overflow is set, just add 0 (not -1)
                    chain.Add(0);
                }
                // if the chain_count dicitionary contains this key and overflow is also set
                if (!chain_count.ContainsKey(i) && this.table[i].overflow != -1)
                {
                    // ternary statement. this math accounts for overflow of overflows.
                    int index = (this.table[i].overflow + 1 >= PRIMARY_TABLE_SIZE) ?
                        (this.table[i].overflow + 1) - (PRIMARY_TABLE_SIZE - 1) : this.table[i].overflow + 1;

                    // counts number of instance index appears in the dictionary
                    chain_count[index] = chain.Count(v => v == index);

                    // add to the collission chain average
                    chain_avg += chain_count[index];
                }
            }

            // calculate the collission chain avrage
            chain_avg /= chain_count.Count();

            for (int i = 0; i < PRIMARY_TABLE_SIZE; ++i)
            {
                // grab the total length of each bucket
                total_length += this.table[i].count;

                // write to the list, which then will be returned and can be used to write to a file.
                lines.Add("Bucket " + (i + 1) + ":");
                lines.Add("\tTotal Length: " + this.table[i].count);
                lines.Add("\n");

                // if count is greater than 1,
                // +1 to the number of buckets which have a more than one slot filled
                // the requirements state not to cound zero length buckets in the average caluclations
                if (this.table[i].count != 0)
                {
                    ++non_zero_length_buckets;
                }
            }

            // calculate the average total length of all primary buckets
            total_length_avg = total_length / non_zero_length_buckets;

            lines.Add("Total Length Average is " + total_length_avg);
            lines.Add("Collission Chain Average is " + chain_avg);

            return lines.ToArray();
        }
Пример #8
0
        /**
         * Searches and retrieves matches using the values from the param
         *
         * @param {string[]} Array of items to search for
         * @returns {string[]} Results of the search in an array, which can be used to write to a file
         * @api public
         */
        public string[] Search(string[] searches)
        {
            bool found;
            int bucket_no;
            int slot_no;

            List<String> lines = new List<String>();

            lines.Add(String.Format("{0,45}", "Search and Retrieval Report"));
            lines.Add(String.Format("{0,38}", "Transactions"));
            lines.Add(String.Format("{0,37}", "Search Key\t\tBucket/Slot\t\tRecord"));

            foreach (string keys in searches)
            {
                // hashed key
                string key = this.Hash(keys.Substring(0, 10));

                found = false;
                bucket_no = 0;
                foreach (Bucket item in this.table)
                {
                    slot_no = 0;
                    foreach(Dictionary<string, Slot> dict in item.slots)
                    {
                        foreach (KeyValuePair<string, Slot> kv in item.slots[slot_no])
                        {

                            // if the two un-hashed keys are equal
                            if (item.slots[slot_no][kv.Key].key == keys.Substring(0, 10))
                            {
                                // found
                                found = true;
                                lines.Add(String.Format("{0,16}{1,16}/{2}\t\t{3}", item.slots[slot_no][kv.Key].key,
                                    bucket_no + 1,
                                    slot_no + 1,
                                    item.slots[slot_no][kv.Key].value
                                ));
                            }
                        }
                        // manual iteration
                        ++slot_no;
                    }
                    // manual iteration
                    ++bucket_no;
                }
                // if nothing was found
                if (!found)
                {
                    lines.Add(String.Format("{0,16}{1,16}/{2,0}\t\t{3,0}",
                        keys.Substring(0, 10),
                        "N",
                        "A",
                        "Record not found"
                    ));
                }
            }
            return lines.ToArray();
        }
Пример #9
0
        /**
         * Generates a report for of the Hash Table contents
         *
         * @returns {string[]} A string array which can be written to a file.
         * @api public
         */
        public string[] GenerateReport()
        {
            List<String> lines = new List<String>();
            int table_no = 0;
            int slot_no;

            lines.Add(String.Format("{0, 37}", "Hash Table"));
            lines.Add(String.Format("{0, 41}", "Verification Report"));
            lines.Add(String.Format("{0, 39}", "Before Report"));

            foreach (Bucket item in this.table)
            {
                lines.Add(String.Format("Bucket {0}", table_no + 1));
                slot_no = 0;
                foreach (Dictionary<string, Slot> dict in item.slots)
                {
                    foreach (KeyValuePair<string, Slot> kv in item.slots[slot_no])
                    {
                        // if there is a key in the slot
                        if (item.slots[slot_no][kv.Key].key != null)
                        {
                            lines.Add(String.Format("\tSlot {0}: {1}{2}",
                                slot_no + 1,
                                item.slots[slot_no][kv.Key].key,
                                item.slots[slot_no][kv.Key].value
                            ));
                        }

                    }
                    // there must be no key
                    if (item.slots[slot_no].Count == 0)
                    {
                        lines.Add(String.Format("\tSlot {0}: None", slot_no + 1));
                    }
                   // manual iteration
                    ++slot_no;
                }
                // if an overflow pointer is set
                if (this.table[table_no].overflow != -1)
                {
                    lines.Add(String.Format("\tOverflow Pointer: {0}", this.table[table_no].overflow + 1));
                }
                else
                {
                    lines.Add(String.Format("\tOveflow Pointer: {0}", "None"));
                }
                lines.Add(String.Format("{0}", "\n"));
                // manual iteration
                ++table_no;
            }
            return lines.ToArray();
        }