Описать класс «множество», позволяющий выполнять основные операции: добавление и удаление элемента - C# (191486)
Формулировка задачи:
Помогите пожалуйста написать.
Каждый разрабатываемый класс должен, как правило, содержать следующие элементы: скрытые поля, конструкторы с параметрами и без параметров, методы; свойства, индексаторы; перегруженные операции. Функциональные элементы класса должны обеспечивать непротиворечивый, полный, минимальный и удобный интерфейс класса. При возникновении ошибок должны выбрасываться исключения.
Само задание: Описать класс «множество», позволяющий выполнять основные операции: добавление и удаление элемента, пересечение, объединение и разность множеств.
Решение задачи: «Описать класс «множество», позволяющий выполнять основные операции: добавление и удаление элемента»
textual
Листинг программы
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApplication195
{
class Program
{
static void Main(string[] args)
{
var set1 = new BloomSet<string>();
var set2 = new BloomSet<string>();
set1.Add("flame");
set2.Add("bloom");
Console.WriteLine(set1.Contains("flame"));
Console.WriteLine(set1.Contains("bloom"));
var set3 = set1 | set2;
Console.WriteLine(set3.Contains("flame"));
Console.WriteLine(set3.Contains("bloom"));
Console.ReadLine();
}
}
/// <summary>
/// Множество Блума
/// </summary>
public class BloomSet<T> : ICollection<T>
{
private uint[] bits;
private int hashSize;
public BloomSet() : this(1024)
{
}
public BloomSet(int hashSize)
{
if (hashSize % 32 != 0 || hashSize <= 0)
throw new ArgumentException("Hash size must be positive and multiple of 32");
this.hashSize = hashSize;
bits = new uint[hashSize / 32];
}
private BloomSet(uint[] bits)
{
this.bits = bits;
hashSize = bits.Length * 32;
}
/// <summary>
/// Adds universal set
/// </summary>
public void AddUniversalSet()
{
for (int i = 0; i < bits.Length; i++)
bits[i] = 0xffffffff;
}
/// <summary>
/// Checks if the set contains given element.
/// Or adds the element to the set.
/// </summary>
public bool this[T item]
{
get { return Contains(item); }
set { if(value) Add(item); }
}
#region ICollection<T> implementation
/// <summary>
/// Adds item to the set
/// </summary>
public void Add(T item)
{
SetBit(GetBitIndex(item));
}
public void Clear()
{
Array.Clear(bits, 0, hashSize);
}
public bool Contains(T item)
{
return IsBit(GetBitIndex(item));
}
public void CopyTo(T[] array, int arrayIndex)
{
//Bloom Set does not allow this
}
public int Count
{
get
{
throw new NotImplementedException("Bloom Set does not allow this method");
}
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
throw new NotImplementedException("Bloom Set does not allow this method");
}
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException("Bloom Set does not allow this method");
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException("Bloom Set does not allow this method");
}
#endregion
#region Private methods
private void SetBit(int iBit)
{
bits[iBit / 32] |= (uint)(1 << (iBit % 32));
}
private void ClearBit(int iBit)
{
bits[iBit / 32] &= ~(uint)(1 << (iBit % 32));
}
private bool IsBit(int iBit)
{
return (bits[iBit / 32] & (uint)(1 << (iBit % 32))) != 0;
}
private int GetBitIndex(T item)
{
return Math.Abs(item.GetHashCode()) % hashSize;
}
#endregion
#region Operators
/// <summary>
/// Union of the sets
/// </summary>
public static BloomSet<T> operator |(BloomSet<T> set1, BloomSet<T> set2)
{
if (set1.hashSize != set2.hashSize)
throw new Exception("Sizes of the sets must be equal");
var bits = (uint[])set1.bits.Clone();
for (int i = 0; i < bits.Length; i++)
bits[i] |= set2.bits[i];
return new BloomSet<T>(bits);
}
/// <summary>
/// Intersection of the sets
/// </summary>
public static BloomSet<T> operator &(BloomSet<T> set1, BloomSet<T> set2)
{
if (set1.hashSize != set2.hashSize)
throw new Exception("Sizes of the sets must be equal");
var bits = (uint[])set1.bits.Clone();
for (int i = 0; i < bits.Length; i++)
bits[i] &= set2.bits[i];
return new BloomSet<T>(bits);
}
/// <summary>
/// Substarction of the sets
/// </summary>
public static BloomSet<T> operator -(BloomSet<T> set1, BloomSet<T> set2)
{
throw new NotImplementedException("Bloom Set does not allow this operator");
}
#endregion
}
}