Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Objects11
- {
- class Program
- {
- static void Main(string[] args)
- {
- var ht = new MyHashTable<int, string>(11);
- ht.Put(23, "aaaa");
- ht.Put(13, "bbb");
- ht.Put(2342, "cccc");
- var v = ht.Get(13);
- Console.WriteLine(v);
- var count = ht.Count;
- Console.WriteLine(count);
- var empty = ht.IsEmpty;
- Console.WriteLine(empty);
- var keys = ht.Keys;
- Console.WriteLine(string.Join(" ", keys));
- Console.ReadLine();
- }
- }
- class MyHashTable<K, V>
- {
- private List<Tuple<K, V>> list;
- public MyHashTable(int capacity)
- {
- list = new List<Tuple<K, V>>(capacity);
- for (int i = 0; i < capacity; i++)
- list.Add(null);
- }
- public void Put(K key, V val)
- {
- var i = GetIndex(key);
- list[i] = new Tuple<K, V>(key, val);
- }
- public V Get(K key)
- {
- var i = GetIndex(key);
- var tuple = list[i];
- if (tuple == null || !tuple.Item1.Equals(key))
- throw new Exception("Key is not found!");
- return tuple.Item2;
- }
- public int Count
- {
- get { return list.Count(t => t != null); }
- }
- public bool IsEmpty
- {
- get { return Count == 0; }
- }
- public IEnumerable<K> Keys
- {
- get { return list.Where(t => t != null).Select(t => t.Item1); }
- }
- int GetIndex(K key)
- {
- return key.GetHashCode() % list.Count;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement