Lớp Set bên dưới sẽ cung cấp cho chúng ta các hàm thực hiện các phép toán trên tập hợp như: Giao, hợp, hiệu:
class Set
{
private string m_Set = "";
#region Contructors
public Set(string str_set)
{
this.m_Set = str_set;
}
#endregion
#region Properties
public string SET
{
get { return m_Set; }
set { m_Set = value; }
}
public int SIZE
{
get { return this.m_Set.Split(new char[1] { ',' }).Length; }
}
#endregion
#region Method
/// <summary>
/// Giao 2 tập hợp
/// </summary>
/// <param name="Set2"></param>
/// <returns>Kết quả của phép giao 2 tập hợp</returns>
public string Intersection(Set Set2)
{
string[] arr_Set1 = this.m_Set.Split(new char[1] { ',' });
string[] arr_Set2 = Set2.SET.Split(new char[1] { ',' });
string Resualt = "";
foreach (string item1 in arr_Set1)
foreach (string item2 in arr_Set2)
if (item1 == item2)
Resualt += item1 + ",";
if (Resualt.Length > 0)
Resualt = Resualt.Substring(0, Resualt.Length - 1);
return Resualt;
}
/// <summary>
/// Hợp 2 tập hợp
/// </summary>
/// <param name="Set2"></param>
/// <returns>Kết quả của phép hợp 2 tập hợp</returns>
public string Union(Set Set2)
{
string[] arr_Set1 = this.m_Set.Split(new char[1] { ',' });
string[] arr_Set2 = Set2.SET.Split(new char[1] { ',' });
string Resualt = "";
if (this.IsNull())
Resualt = Set2.SET;
else if (Set2.IsNull())
Resualt = this.SET;
else
{
Resualt = this.SET + ",";
foreach (string item2 in arr_Set2)
{
bool exits = false;
foreach (string item1 in arr_Set1)
{
if (item1 == item2)
{
exits = true;
break;
}
}
if (exits == false)
Resualt += item2 + ",";
}
if (Resualt.Length > 0)
Resualt = Resualt.Substring(0, Resualt.Length - 1);
}
return Resualt;
}
/// <summary>
/// Hiệu 2 tập hợp
/// </summary>
/// <param name="Set2"></param>
/// <returns>Kết quả hiệu 2 tập hợp</returns>
public string Minus(Set Set2)
{
string[] arr_Set1 = this.m_Set.Split(new char[1] { ',' });
string[] arr_Set2 = Set2.SET.Split(new char[1] { ',' });
string Resualt = "";
foreach (string item1 in arr_Set1)
{
bool exits = false;
foreach (string item2 in arr_Set2)
{
if (item1 == item2)
{
exits = true;
break;
}
}
if (exits == false)
Resualt += item1 + ",";
}
if (Resualt.Length > 0)
Resualt = Resualt.Substring(0, Resualt.Length - 1);
return Resualt;
}
/// <summary>
/// Kiểm tra tập hợp có là tập rỗng hay không?
/// </summary>
/// <returns></returns>
public bool IsNull()
{
bool resualt = true;
if (this.m_Set.Length > 0)
resualt = false;
return resualt;
}
#endregion
}
Nosomovo