集合:算法
聯合、交叉、差別、子集數據結構
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; } } }