排列数据结构
本文关键字:数据结构 排列 | 更新日期: 2023-09-27 18:12:26
我需要一些关于排列的帮助。
我的问题是:在我们的系统中,我们有不同的设备运行不同的软件组件。我对找到上述组件的所有版本的排列(唯一组合)很感兴趣,最后得到一个元组或结构体的列表,如
struct Permutation
{
IComparable Software1{ get; set; }
IComparable Software2{ get; set; }
IComparable Software3{ get; set; }
}
然后以这样的列表结尾:
Software1: v1
Software2: v1
Software3: v1
Software1: v1
Software2: v2
Software3: v1
Software1: v2
Software2: v1
Software3: v1
软件存在于以树状结构(Node->Item)组织的各种组件上。子节点的类型告诉我要查找哪种软件
Node->Root (L0)
Node->Parent (L1)
Node->ChildType1 (L2): has property Software1, Software2
Node->ChildType2 (L2): has property Software3
我可以很容易地用node.Children
(IList<Node>
)和node.Parent
(Node
)导航树。
我想对树进行无序迭代,并构建一个包含所有排列的列表。在。net框架中是否有一个良好的现有数据结构,我可以使用它,或者有人对如何解决它有任何建议吗?
我的想法是:
var list = from parent in root.Parents()
select new Permutation
{
Software1 = parent.ChildA.Software1,
Software2 = parent.ChildA.Software2,
Software3 = parent.ChildB.Software3,
};
foreach (var perm in list.Distinct())
{
// do something
}
您需要确保Permutation是可比较且可等价的:
struct Permutation : IEquatable<Permutation>, IComparable<Permutation>
{
public IComparable Software1 { get; set; }
public IComparable Software2 { get; set; }
public IComparable Software3 { get; set; }
public bool Equals(Permutation other)
{
return Equals(other.Software1, Software1) && Equals(other.Software2, Software2) && Equals(other.Software3, Software3);
}
public int CompareTo(Permutation other)
{
int cmp = 0;
if (0 == cmp) cmp = other.Software1.CompareTo(Software1);
if (0 == cmp) cmp = other.Software2.CompareTo(Software2);
if (0 == cmp) cmp = other.Software3.CompareTo(Software3);
return cmp;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Permutation)) return false;
return Equals((Permutation)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (Software1 != null ? Software1.GetHashCode() : 0);
result = (result * 397) ^ (Software2 != null ? Software2.GetHashCode() : 0);
result = (result * 397) ^ (Software3 != null ? Software3.GetHashCode() : 0);
return result;
}
}
public static bool operator ==(Permutation left, Permutation right)
{
return left.Equals(right);
}
public static bool operator !=(Permutation left, Permutation right)
{
return !left.Equals(right);
}
}
我用了resharper来做跑腿的工作:)