Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class HashSetMy<T> : IEnumerable<T>
- {
- private const int MIN_BUFFER_SIZE = 16;
- private const int RESIZE_FACTOR = 2;
- private const double FULL_FACTOR = 0.7;
- private List<T>[] buffer;
- public int Count { get; private set; }
- public HashSetMy(int size = MIN_BUFFER_SIZE)
- {
- buffer = new List<T>[size];
- this.Count = 0;
- }
- public bool AddItem(T value)
- {
- var hash = (uint)value.GetHashCode();
- var index = hash % buffer.Length;
- var existed = buffer[index] != null && buffer[index].Contains(value);
- if (existed)
- {
- return false;
- }
- if (buffer[index] == null)
- {
- buffer[index] = new List<T>();
- }
- buffer[index].Add(value);
- this.Count++;
- if ((double)this.Count / buffer.Length > FULL_FACTOR)
- {
- this.Resize(buffer.Length * RESIZE_FACTOR);
- }
- return true;
- }
- public bool Contains(T value)
- {
- var hash = (uint)value.GetHashCode();
- var index = hash % buffer.Length;
- return buffer[index] != null && buffer[index].Contains(value);
- }
- public bool Remove(T value)
- {
- var hash = (uint)value.GetHashCode();
- var index = hash % buffer.Length;
- if (buffer[index] == null)
- {
- return false;
- }
- return this.buffer[index].Remove(value);
- }
- private void Resize(int newSize)
- {
- var newBuffer = new List<T>[newSize];
- foreach (var x in this)
- {
- var hash = (uint)x.GetHashCode();
- var index = hash % newSize;
- if (newBuffer[index] == null)
- {
- newBuffer[index] = new List<T>();
- }
- newBuffer[index].Add(x);
- }
- this.buffer = newBuffer;
- }
- public IEnumerator<T> GetEnumerator()
- {
- foreach (var list in buffer)
- {
- if (list == null)
- {
- continue;
- }
- foreach (var x in list)
- {
- yield return x;
- }
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return this.GetEnumerator();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement