簡體   English   中英

有一個矩陣字典,如何返回一個包含最小數目為零的矩陣的字典?

[英]having a dictionary of matrices, how to return a dictionary containing the matrix with the smallest number of zeros?

我有一個包含矩陣的字典,我想為每個矩陣計數零的數目,並返回一個包含最小為零的元素的字典。為此,我已經有一種方法來計數零的數目,以及如何擁有矩陣最小值為零,但我不知道如何返回該對。

在此處輸入圖片說明

Dictionary<string, int[,]> c
        foreach ( int[,] entry in c.Values)
        {
            //array to contain the number of zeros
              int[] max_couverture = new int[c.Count];
                for (int i = 0; i < max_couverture.Length; i++)
                {
             //calcul_zero the method that calculate the number of zero of a matrix
                    max_couverture[i] = calcul_zero(entry);
                }
                int min = max_couverture[0];
                for (int i = 0; i < max_couverture.Length; i++)
                {
                    if (max_couverture[i] < min) min = max_couverture[i];

                    i++;
                }


        }
//calculate the number of zero of a matrix
 public static  int calcul_zero(int[,] m)
    {
        int colIdx = 0; // column index to check
        int num = Enumerable.Range(0, m.GetLength(0)).Count(i => m[i, colIdx] == 0);
        return num;
    }

可以通過使用分解問題來使用已經存在的設施來解決該問題。 首先,不幸的是, int[,]沒有實現IEnumerable<int> ,可以使用以下擴展方法對其進行尋址。

public static IEnumerable<T> ToEnumerable<T>(this T[,] target)
{
    foreach (var item in target)
    {
        yield return item;
    }
}

接下來,我們可以使用Linq定義一個函數,該函數計算二維數組中的零個數,如下所示。

public static int CountZeros(int[,] iMat)
{
    return iMat.ToEnumerable<int>().Count(iInt => 0 == iInt);
}

意外的是,Linq還沒有提供擴展方法來確定序列中的某個元素(如果對其施加了某種功能)是最大還是最小。 這可以通過以下兩種擴展方法來完成。

public static T ArgMin<T, R>(T t1, T t2, Func<T, R> f)
where R : IComparable<R>
{
    return f(t1).CompareTo(f(t2)) > 0 ? t2 : t1;if equal
}

public static T ArgMin<T, R>(this IEnumerable<T> Sequence, Func<T, R> f)
where R : IComparable<R>
{
    return Sequence.Aggregate((t1, t2) => ArgMin<T, R>(t1, t2, f));
}

最后,我們可以定義一個返回字典的方法,該字典包含零個數最小的第一個鍵和值矩陣。

public static Dictionary<string, int[,]> MinNumOfZeros(Dictionary<string, int[,]> iDict)
{
    var KeyOfMinimum = iDict.Keys.ArgMin(iKey => CountZeros(iDict[iKey]));
    return new Dictionary<string, int[,]> { { KeyOfMinimum, iDict[KeyOfMinimum] } };
}

您可以通過稍微修改calcul_zero來實現。 即:

{
// ...
var minKV = c.ToList()
    .OrderBy(k => calcul_zero(k.Value))
    .First();

Console.WriteLine(minKV.Key);
//...
}
public static int calcul_zero(int[,] m)
{
    int zeros=0;
    for (int i = 0; i < m.GetLength(0); i++)
    {
        for (int j = 0; j < m.GetLength(1); j++)
        {
            if (m[i, j] == 0) zeros++;
        }
    }
    return zeros;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM