using System;
using System.Collections;
using System.Collections.Generic;
namespace Advanced.Algorithms.DataStructures.Foundation
{
///
/// A hash table implementation.
///
/// The value datatype.
public class HashSet : IEnumerable
{
private readonly IHashSet hashSet;
/// The hashSet implementation to use.
/// The larger the bucket size lesser the collision, but memory matters!
public HashSet(HashSetType type = HashSetType.SeparateChaining, int initialBucketSize = 2)
{
if (initialBucketSize < 2)
{
throw new Exception("Bucket Size must be greater than 2.");
}
if (type == HashSetType.SeparateChaining)
{
hashSet = new SeparateChainingHashSet(initialBucketSize);
}
else
{
hashSet = new OpenAddressHashSet(initialBucketSize);
}
}
///
/// The number of items in this hashset.
///
public int Count => hashSet.Count;
///
/// Does this hash table contains the given value.
/// Time complexity: O(1) amortized.
///
/// The value to check.
/// True if this hashset contains the given value.
public bool Contains(T value)
{
return hashSet.Contains(value);
}
///
/// Add a new value.
/// Time complexity: O(1) amortized.
///
/// The value to add.
public void Add(T value)
{
hashSet.Add(value);
}
///
/// Remove the given value.
/// Time complexity: O(1) amortized.
///
/// The value to remove.
public void Remove(T value)
{
hashSet.Remove(value);
}
///
/// Clear the hashtable.
/// Time complexity: O(1).
///
public void Clear()
{
hashSet.Clear();
}
IEnumerator IEnumerable.GetEnumerator()
{
return hashSet.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return hashSet.GetEnumerator();
}
}
internal interface IHashSet : IEnumerable
{
bool Contains(T value);
void Add(T value);
void Remove(T key);
void Clear();
int Count { get; }
}
///
/// The hash set implementation type.
///
public enum HashSetType
{
SeparateChaining,
OpenAddressing
}
}