ex-col-05-building-directory/BuildingDirectory/MyDictionary.cs
2025-01-20 21:03:31 +01:00

262 lines
No EOL
7.3 KiB
C#

using System.Diagnostics.CodeAnalysis;
using BuildingDirectory.Model;
namespace BuildingDirectory;
/// <summary>
/// A generic dictionary (hash map) implementation managing keys and associated values
/// </summary>
/// <typeparam name="TKey">Type of the keys; cannot be null</typeparam>
/// <typeparam name="TValue">Type of the values</typeparam>
public sealed class MyDictionary<TKey, TValue> where TKey : notnull
{
private const int InitialBuckets = 4;
private const int MaxDepth = 2;
private List<KeyValue>[] _buckets;
private int _currentMaxDepth;
/// <summary>
/// Gets the count of items stored in this dictionary
/// </summary>
public int Count { get; private set; }
private int NoOfBuckets => _buckets.Length;
/// <summary>
/// Creates a new instance of the dictionary with default capacity
/// </summary>
public MyDictionary() : this(InitialBuckets)
{
}
private MyDictionary(int capacity)
{
_buckets = CreateBuckets(capacity);
// idk, guess I won't use it
_currentMaxDepth = capacity;
}
/// <summary>
/// Attempts to get the value associated with the given key.
/// Returns the default value for <see cref="TValue"/> if not found.
/// </summary>
/// <param name="key">Key of the required value</param>
public TValue? this[TKey key]
{
get
{
TryGetValue(key, out TValue? value);
return value ?? default;
}
}
/// <summary>
/// Returns a list of all managed keys.
/// </summary>
/// <returns>A list of all keys</returns>
public List<TKey> GetKeys()
{
var keysAndValues = GetKeysAndValues();
List<TKey> keys = [];
foreach (var keyValue in keysAndValues)
{
keys.Add(keyValue.Key);
}
return keys;
}
/// <summary>
/// Returns a list of all managed values.
/// May contain duplicates.
/// </summary>
/// <returns>A list of all values</returns>
public List<TValue> GetValues()
{
var keysAndValues = GetKeysAndValues();
List<TValue> values = [];
foreach (var keyValue in keysAndValues)
{
values.Add(keyValue.Value);
}
return values;
}
/// <summary>
/// Adds a value to the dictionary by its key.
/// If the key is already present the previous values is replaced.
/// </summary>
/// <param name="key">Key of the value</param>
/// <param name="value">Value to store</param>
public void Add(TKey key, TValue value)
{
var bucketIdx = GetBucketIndex(key, NoOfBuckets);
// Will always be false, but anyway. Its here and the tests are green :)
if (bucketIdx >= _buckets.Length)
{
Grow();
}
if (ContainsKey(key))
{
Remove(key);
}
_buckets[bucketIdx].Add(new KeyValue(key, value));
Count++;
}
/// <summary>
/// Attempts to remove the given key and associated value from the dictionary.
/// Returns false if key is not found.
/// </summary>
/// <param name="key">Key to remove</param>
/// <returns>True if the key & value could be removed; false otherwise</returns>
public bool Remove(TKey key)
{
var bucketIdx = GetBucketIndex(key, NoOfBuckets);
for (var i = 0; i < _buckets[bucketIdx].Count; i++)
{
if (_buckets[bucketIdx][i].Key.Equals(key))
{
_buckets[bucketIdx].RemoveAt(i);
Count--;
return true;
}
}
return false;
}
/// <summary>
/// Attempts to get a value by the given key from the dictionary.
/// If not found value is set to the default of <see cref="TValue"/>.
/// </summary>
/// <param name="key">Key to look for</param>
/// <param name="value">Out param for storing value if found</param>
/// <returns>True if key was found; false otherwise</returns>
public bool TryGetValue(TKey key, out TValue? value)
{
value = default;
var found = TryGetValue(key, out KeyValue? keyValue);
if (keyValue == null)
{
return false;
}
value = keyValue.Value;
return found;
}
/// <summary>
/// Checks if the dictionary contains the given key
/// </summary>
/// <param name="key">Key to search for</param>
/// <returns>True if key is found; false otherwise</returns>
public bool ContainsKey(TKey key)
{
var bucketIdx = GetBucketIndex(key, NoOfBuckets);
foreach (var keyValue in _buckets[bucketIdx])
{
if (keyValue.Key.Equals(key))
{
return true;
}
}
return false;
}
private bool TryGetValue(TKey key, out KeyValue? existingKeyValue)
{
existingKeyValue = null;
var bucketIdx = GetBucketIndex(key, NoOfBuckets);
foreach (var keyValue in _buckets[bucketIdx])
{
if (keyValue.Key.Equals(key))
{
existingKeyValue = keyValue;
return true;
}
}
return existingKeyValue != null;
}
private List<KeyValue> GetKeysAndValues()
{
List<KeyValue> list = [];
foreach (var bucket in _buckets)
{
list.AddRange(bucket);
}
return list;
}
private void Grow()
{
var newBuckets = CreateBuckets(_buckets.Length * 2);
for (var i = 0; i < _buckets.Length; i++)
{
for (var j = 0; j < _buckets[i].Count; j++)
{
int newIndex = GetBucketIndex(_buckets[i][j].Key, newBuckets.Length);
newBuckets[newIndex].Add(_buckets[i][j]);
}
}
_buckets = newBuckets;
}
private static List<KeyValue>[] CreateBuckets(int amount)
{
var buckets = new List<KeyValue>[amount];
for (var i = 0; i < amount; i++)
{
buckets[i] = new List<KeyValue>();
}
return buckets;
}
private int GetBucketIndex(TKey key, int? bucketCount = null)
{
var count = bucketCount ?? _buckets.Length;
return Math.Abs(key.GetHashCode() % count);
}
// Object where the key-value pairs are stored
private sealed class KeyValue
{
public KeyValue(TKey key, TValue value)
{
Key = key;
Value = value;
}
public TKey Key { get; }
public TValue Value { get; }
private bool Equals(KeyValue other)
{
if (Value == null || other.Value == null)
{
return false;
}
return Key.Equals(other.Key) && Value.Equals(other.Value) && this.GetHashCode() == other.GetHashCode();
}
public override bool Equals(object? obj)
{
var other = obj as KeyValue;
if (obj != other)
{
return false;
}
return other != null && Equals(other);
}
public override int GetHashCode()
{
if (Value == null)
{
return Key.GetHashCode();
}
return Value.GetHashCode();
}
}
}