2010-08-13 42 views
0

考慮以下代碼:如何獲得用任何兩個數組值調用的函數的所有可能值?

class MyClass { 
    string PropertyA; 
    int PropertyB; 
    double PropertyC; 
    object PropertyD; 
    static ComparisonResult Compare(MyClass a, MyClass b){ 
     // returns a ComparisonResult with 
     // _sampleElement = a 
     // _commonProperties = flags that describe the common properties of a and b 
    } 
} 

enum SimilarityFlags { 
    SharedPropertyA = 1, 
    SharedPropertyB = 2, 
    SharedPropertyC = 4, 
    SharedPropertyD = 8 
} 

class ComparisonResult { 
    private MyClass _sampleElement; 
    private SimilarityFlags _commonProperties; 

    bool Equals(object obj){ 
     ComparisonResult other = obj as ComparisonResult; 
     if(other==null) return false; 
     if(this._commonProperties != other._commonProperties) return false; 
     MyClass s1 = this._sampleElement; 
     MyClass s2 = other._sampleElement; 
     if(_commonProperties.HasFlag(SimilarityFlags.SharedPropertyA) && s1.PropertyA != s2.PropertyA) return false; 
     if(_commonProperties.HasFlag(SimilarityFlags.SharedPropertyB) && s1.PropertyB != s2.PropertyB) return false; 
     if(_commonProperties.HasFlag(SimilarityFlags.SharedPropertyC) && s1.PropertyC != s2.PropertyC) return false; 
     if(_commonProperties.HasFlag(SimilarityFlags.SharedPropertyD) && s1.PropertyD != s2.PropertyD) return false; 
     return true; 
    } 

    int GetHashCode(){ 
     return (int)_commonProperties; 
    } 
} 



MyClass[] array; 
HashSet<ComparisonResult> possibleValues = GetAllPossibleComparisonValues(array); 

我怎樣才能得到所有的收益比較時,需要在陣列中任意兩個元素的可能值?

!注:比較(A,B)==比較(B,A)和A = B

實施例(僞代碼,3個屬性,而不是4):

GetAllPossibleComparisonValues([ {"foo", 5, 0x00}, {"foo", 77, 0x00}, {"BAR", 5, 0x00}, {"foo", 5, 0x00}, {"BAR", 5, 0x00} ]) 

應返回此設置: [{any,any,0x00},{「foo」,any,0x00},{「foo」,5,0x00},{「BAR」,5,0x00},{any,5,0x00}]

GetAllPossibleComparisonValues([ {"foobar", 1}, {"foobar", 2}, {"foobar", 3}, {"foobar", 4} ]) 

應返回 [{ 「foobar的」,任何}]

目前,我使用的這個算法:

for(int i = 0; i < array.Length - 1; i++){ 
    for(int j = i + 1; i < array.Length; j++){ 
     possibleValues.Add(MyClass.Compare(array[i], array[j])); 
    } 
} 

,但它是非常低效的,尤其是長陣列,其中任何兩個元素具有相同的ComparisonResult。 計算後,possibleValues.Count通常非常小(1..3),即使對於長數組(2000+元素)也是如此。

我認爲可以大大提高計算效率。例如,如果Compare(array [0],array [1])== Compare(array [0],array [2]),則不需要調用Compare(array [1],array [2])

我該怎麼辦?

回答

0

這個問題似乎是boolean satisfiability problem。如果將數組的每個值作爲布爾輸入變量進行建模,則可以使用維基百科頁面中列出的算法來獲取滿足特定輸出變量的所有輸入向量。這種努力並不低,所以這取決於你是否真的需要這種加速,或者你是否能夠使用你的早期工作解決方案,因爲這很容易理解。

另一件事可能是你緩存你已找到的解決方案,只修改那些找到的向量,如果一個數組中的新值已被添加。這樣你只需要首先找到解矢量。如果你可以應用這個依賴天氣,可能的值會經常變化,或者如果它們沒有變化太大。

相關問題