2011-10-24 61 views
0

我需要關於排列的一些幫助。排列數據結構

我的問題是這樣的:在我們的系統中,我們有各種運行各種軟件組件的設備。

Software1: v1 
Software2: v1 
Software3: v1 

Software1: v1 
Software2: v2 
Software3: v1 

Software1: v2 
Software2: v1 
Software3: v1 
:IM有意尋找說組件的版本的所有排列(獨特的組合),並與元組或結構的ALA這

struct Permutation 
{ 
    IComparable Software1{ get; set; } 
    IComparable Software2{ get; set; } 
    IComparable Software3{ get; set; } 
} 

列表結束,然後用像這樣的列表結束

該軟件存在於以樹結構(節點 - >項目)組織的各種組件中。該類型的子節點的告訴我,看看哪一種軟件了

Node->Root (L0) 
    Node->Parent (L1) 
     Node->ChildType1 (L2): has property Software1, Software2 
     Node->ChildType2 (L2): has property Software3 

我可以很容易地node.ChildrenIList<Node>)和node.ParentNode)瀏覽樹。

我想按順序迭代樹並構建所有排列的列表。 .net框架中是否存在一個很好的現有數據結構,我可以使用它,或者有沒有人對如何解決它有任何建議?

+0

你應該顯示一些代碼;我很難弄清楚這棵樹現在爲我排序了什麼\ – sehe

+0

我剛剛在我的網站上寫了一篇有關通用樹結構的文章。也許這會有所幫助。 [通用訪問者模式](http://www.segerlabs.com/generic-visitor-pattern.aspx) –

回答

1

我的想法是沿着這些路線:

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 
    } 

你要確保置換相媲美,並equatable就好:

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的做跑腿有:)

+0

謝謝,不同的功能會做的伎倆:) – havardhu

+0

@havardhu:不要忘記比較器(默認情況下Distinct()使用由'EqualityComparer '泛型類的['Default'](http://msdn.microsoft.com/en-us/library/ms224763.aspx)屬性提供的默認實現,這就是爲什麼我該結構實現'IEquatable ' – sehe