集合:
联合、交叉、差异、子集
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 数据结构和算法
{ public partial class SCet
{
static void Main()
{
SCet setA = new SCet();
SCet setB = new SCet();
setA.Add("milk");
setA.Add("eggs");
setA.Add("bacon");
setA.Add("cereal");
setB.Add("bacon");
setB.Add("eggs");
setB.Add("bread");
SCet setC = new SCet();
setC = setA.Union(setB);
Console.WriteLine();
Console.WriteLine("A: " + setA);
Console.WriteLine("B: " + setB.ToString());
Console.WriteLine("A union B: " + setC.ToString());
setC = setA.Intersection(setB);
Console.WriteLine("A intersect B: " + setC.ToString());
setC = setA.Difference(setB);
Console.WriteLine("A diff B: " + setC.ToString());
setC = setB.Difference(setA);
Console.WriteLine("B diff A: " + setC.ToString());
if (setB.Subset(setA))
Console.WriteLine("b is a subset of a");
else
Console.WriteLine("b is not a subset of a"); Console.Read();
}
} public partial class SCet
{
private Hashtable data;
public SCet()
{
data = new Hashtable();
}
//More code to follow public void Add(Object item)
{
if (!data.ContainsValue(item))
{
data.Add(Hash(item), item);
}
} public string Hash(object item)
{
char[] chars;
string s = item.ToString();
int hashValue = 0;
chars = s.ToCharArray();
for (int i = 0; i <= chars.GetUpperBound(0); i++)
{
hashValue += (int)chars[i];
}
return hashValue.ToString();
} public void Remove(object item)
{
data.Remove(Hash(item));
} public int Size()
{
return data.Count;
} //联合:把一个集合的成员与另一个集合的成员合并从而获得新的集合。
public SCet Union(SCet aSet)
{
SCet tempSet = new SCet();
foreach (var hashObject in data.Keys)
{
tempSet.Add(data[hashObject]);
}
foreach (var hashObject in aSet.data.Keys)
{
if (!data.ContainsKey(hashObject))
{
tempSet.Add(aSet.data[hashObject]);
}
}
return tempSet;
} //交叉:把已经存在于另一个集合的所有成员添加给一个集合从而获得新的集合。
public SCet Intersection(SCet aSet)
{
SCet tempSet = new SCet();
foreach (var hashObject in data.Keys)
{
if (aSet.data.Contains(hashObject))
{
tempSet.Add(aSet.data[hashObject]);
}
}
return tempSet;
} //是否为子集
public bool Subset(SCet aSet)
{
if (this.Size() > aSet.Size())
return false;
else
foreach (Object key in this.data.Keys)
{
if (!(aSet.data.Contains(key)))
return false;
}
return true;
} //差异:把不存在于另一个集合的所有成员添加给一个集合从而获得新的集合。
public SCet Difference(SCet aSet)
{
SCet tempSet = new SCet();
foreach (Object hashObject in data.Keys)
{
if (!(aSet.data.Contains(hashObject)))
tempSet.Add(data[hashObject]);
}
return tempSet;
} public override string ToString()
{
string s = "";
foreach (Object key in data.Keys)
s += data[key] + " ";
return s;
}
}
}