【问题标题】:How can I find biggest number in a specific row of 2d array?如何在二维数组的特定行中找到最大数?
【发布时间】:2020-01-04 17:13:41
【问题描述】:

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

  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 那行我必须找到最大的值

【问题讨论】:

  • 我建议您使用比ji 更具描述性的标识符。例如,方法名为BiggestValueOfKRow - 所以j 应该重命名为kkthRowIndex 才能清楚。
  • matrica.n 指的是什么?是矩阵的宽度还是矩阵的总细胞数?或者是其他东西? (这就是描述性名称很重要的原因)。
  • 矩阵是列优先还是行优先?
  • TakeValue的定义是什么?为什么要使用自定义矩阵类而不是原生 2D 数组或锯齿状数组?
  • 该方法名为BiggestValue...,但其输出参数返回一个索引——在这种情况下,该方法应重命名为GetIndexOfMaxValueOfKthRow。当索引 i 和值 max 共享相同类型 (Int32) 时,命名很重要。

标签: c# multidimensional-array


【解决方案1】:

假设Matrix::TakeValue(a,b) 是列优先且Matrix::n 是矩阵的绝对宽度(即,独占上界,而不是包容性上界),这就是我将如何使用@ 987654323@:

// 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2013-05-03
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2021-02-18
    • 2022-11-01
    • 2016-08-24
    相关资源
    最近更新 更多