using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 数据结构和算法 { public partial class CSet { static void Main() { } } public partial class CSet { private Hashtable data; public CSet() { 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 CSet Union(CSet aSet) { CSet tempSet = new CSet(); foreach (var hashObject in data.Keys) { tempSet.Add(this.data[hashObject]); } foreach (var hashObject in aSet.data.Keys) { if (!data.ContainsKey(hashObject)) { tempSet.Add(aSet.data[hashObject]); } } return tempSet; } // public CSet Intersection(CSet aSet) { CSet tempSet = new CSet(); foreach (var hashObject in data.Keys) { if (aSet.data.Contains(hashObject)) { tempSet.Add(aSet.data[hashObject]); } } return tempSet; } public bool Subset(CSet 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 CSet Difference(CSet aSet) { CSet tempSet = new CSet(); 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; } } }
时间: 2024-10-17 20:00:16