考慮以下代碼:如何獲得用任何兩個數組值調用的函數的所有可能值?
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])
我該怎麼辦?