[英]Find intersection of two multi-dimensional Arrays in C# 4.0
試圖找到解決我排名問題的方法。
基本上,我有兩個多維double [,]數組。 兩者都包含某些方案的排名,因此[等級編號,方案編號]。 一個以上的場景可以具有相同的等級。
我想生成第三個多維數組,並采用前兩個多維數組的交集提供聯合排名。
有誰知道如何在C#中做到這一點?
非常感謝您提供的任何建議或幫助!
編輯:
感謝您的所有答復,對不起,我應該提供一個示例。
這里是:
Array One:
[{0,4},{1,0},{1,2},{2,1},{3,5},{4,3}]
Array Two:
[{0,1},{0,4},{1,0},{1,2},{3,5},{4,3}]
Required Result:
[{0,4},{1,0},{1,2},{1,1},{2,5},{3,3}]
以下是一些示例代碼,這些代碼做出了一系列假設,但可能與您正在尋找的東西類似。 我還添加了一些評論:
static double[,] Intersect(double[,] a1, double[,] a2)
{
// Assumptions:
// a1 and a2 are two-dimensional arrays of the same size
// An element in the array matches if and only if its value is found in the same location in both arrays
// result will contain not-a-number (NaN) for non-matches
double[,] result = new double[a1.GetLength(0), a1.GetLength(1)];
for (int i = 0; i < a1.GetLength(0); i++)
{
for (int j = 0; j < a1.GetLength(1); j++)
{
if (a1[i, j] == a2[i, j])
{
result[i, j] = a1[i, j];
}
else
{
result[i, j] = double.NaN;
}
}
}
return result;
}
在大多數情況下,找到多維數組的交集將涉及迭代數組中每個維度中的元素。 如果數組的索引不是匹配條件的一部分(刪除了我在代碼中的第二個假設),則必須遍歷每個數組中的每個維度-這會增加算法的運行時間(在這種情況下, O(n ^ 2)至O(n ^ 4)。
如果您足夠在意運行時,我相信數組匹配是動態編程(DP)優化的典型示例之一。 您可以在閑暇時閱讀。
我不確定您希望如何得到結果...您可能會返回一個可以按對建立索引的結果平面集合,如果預期結果集通常很小,則可能節省大量空間。 我選擇了第三個固定大小的數組,因為這是最簡單的操作。
最后,我要提到的是,我沒有看到使用IEnumerable,LINQ或類似方法執行C#的敏銳方式。 比我現在任何時候都鍾聲的C#知識淵博。
考慮到其他信息,我認為您實際上不是在處理多維數組,而是在處理對的集合。 這對是一對雙打。 我認為以下應該很好地工作:
public class Pair : IEquatable<Pair>
{
public double Rank;
public double Scenario;
public bool Equals(Pair p)
{
return Rank == p.Rank && Scenario == p.Scenario;
}
public override int GetHashCode()
{
int hashRank= Rank.GetHashCode();
int hashScenario = Scenario.GetHashCode();
return hashRank ^ hashScenario;
}
}
然后,您可以在IEnumerable上使用Intersect運算符:
List<Pair> one = new List<Pair>();
List<Pair> two = new List<Pair>();
// ... populate the lists
List<Pair> result = one.Intersect(two).ToList();
請查看有關Enumerable.Intersect()的以下msdn文章,以了解更多信息: http : //msdn.microsoft.com/zh-cn/library/bb910215%28v=vs.90%29.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.