Lucio Flores
2022-02-15T02:01:47Z

SimpleHashTableImplementation.cs

| using System;
|
| namespace DataStructures.HashTable
| {
| class Program
| {
| static void Main(string[] args)
| {
| Console.WriteLine("Hello World!");
| int len = 100;
| string keyPrexix = "myKey";
| var myHashTable = new MyHashTable(len);
| var rnd = new Random(7);
| for(int i = 0; i < len; i++)
| {
| myHashTable.Set($"{keyPrexix}{i}", rnd.Next());
| }
| for (int i = 0; i < len; i++)
| {
| var currentItem = myHashTable.Get($"{keyPrexix}{i}");
| Console.WriteLine($"Address:{currentItem.Address}, Key: {currentItem.Key}, Value: {currentItem.Value}");
| }
| }
| }
|
| class MyHashItem
| {
| public string Key { get; set; }
| public int Value { get; set; }
| public int Address { get; set; }
| }
|
|
| class MyHashTable
| {
| private MyHashItem[] _myArray;
| private int _size;
|
| public MyHashTable(int size)
| {
| _size = size;
| _myArray = new MyHashItem[size];
| }
|
| private int _hash(string key)
| {
| int hash = 0;
| for(int i = 0; i < key.Length; i++)
| {
| hash = (hash + key[i] * i) % _myArray.Length;
| }
| return hash;
| }
|
| public void Set(string key, int value)
| {
| //first step to store data: get a hash for the key.
| var address = this._hash(key);
|
| //check if the item already exists
| //hashtables don't allow repeated items
| var item = Get(key);
| if (item != null)
| {
| return;
| }
|
| if(_myArray[address] == null)
| {
| _myArray[address] = new MyHashItem { Key = key, Value = value, Address = address };
| }
| else
| {
| int firstAvailable = GetFirstAvailablePosition();
| _myArray[firstAvailable] = new MyHashItem { Key = key, Value = value, Address = firstAvailable };
| }
| }
| public MyHashItem Get(string key)
| {
| var address = this._hash(key);
| var obj = _myArray[address];
| if(obj != null)
| {
| if (obj.Key == key) return obj;
| else
| {
| return GetItem(key);
| }
| }
|
| else return null;
| }
|
| private int GetFirstAvailablePosition()
| {
| for(int i = 0; i < _size; i++)
| {
| if (_myArray[i] == null) return i;
| }
| throw new OutOfMemoryException();
| }
|
| private MyHashItem GetItem(string key)
| {
| for (int i = 0; i < _size; i++)
| {
| if (_myArray[i] != null)
| {
| if (_myArray[i].Key == key) return _myArray[i];
| }
| }
| return null;
| }
| }
| }