首页 > 解决方案 > 如何在二维数组的特定行中找到最大数?

问题描述

我需要找到二维数组中特定行的最大值。

  static void BiggestValueOfKRow(Matrix matrica, int j, out int maxI)
             {
                int max = matrica.TakeValue(0,j);
                maxI = 0;
                for (int i = 0; i < matrica.n; i++)
                {
                    if (matrica.TakeValue(i, j) > max)
                    {
                        max = matrica.TakeValue(i, j);
                        maxI = i;
                    }
                }
            }

我之前尝试过其他选项,但我仍然无法获得它。我应该能够选择行号然后 int 那行我必须找到最大的值

标签: c#multidimensional-array

解决方案


假设这Matrix::TakeValue(a,b)是列主要的并且Matrix::n是矩阵的绝对宽度(即排他上界,而不是包容性上界),这就是我的做法,使用MaxBy

// Requires C# 7.3 for the use of value-tuples:

static (Int32 columnIndex, Int32 value) GetRowMax( Matrix m, int rowIndex )
{
    if( m == null ) throw new ArgumentNullException( nameof(m) );

    return Enumerable
        .Range( 0, m.n )
        .Select( colIdx => ( columnIndex: colIdx, value: m.TakeValue( colIdx, rowIndex ) ) )
        .MaxBy( t => t.value );
}

请注意,这MaxBy不是普通 Linq (grrr) 的一部分,但它包含在几乎所有体面的 Linq 扩展库中,例如 Jon Skeet 的 MoreLINQ。

MaxBy下面提供了一个实现:

// Rather than defining `MaxBy` yourself, you can also use MoreLINQ from NuGet.

static class LinqExtensions
{
    public static T MaxBy<T,TValue>( this IEnumerable<T> source, Func<T,TValue> selector )
        where TValue : IComparable<TValue>
    {
        if( source == null ) throw new ArgumentNullException( nameof(source) );
        if( selector == null ) throw new ArgumentNullException( nameof(selector) );

        TValue max = default(TValue);
        foreach( T item in source )
        {
            if( item != null && item.CompareTo( max ) > 0 )
            {
                max = item;
            }
        }

        return max;
    }
}

推荐阅读