c# - 如何在二维数组的特定行中找到最大数?
问题描述
我需要找到二维数组中特定行的最大值。
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 那行我必须找到最大的值
解决方案
假设这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;
}
}
推荐阅读
- c# - 在 3D 环境中照亮 2D 网格
- mysql - 使用来自主查询的数据的 MySQL 嵌套选择查询
- glsl - OpenGL顶点着色器处理
- python - 从其他数组创建新数组
- c++ - SFML和glad可以在同一个项目中使用吗
- android - 离子电容器“PushNotifications”插件未在 android 上实现
- c - C 中的函数 log(x) 总是给出相同的值
- xml - 如何使用 XmlSlurper 在 Groovy 中通过标签和属性查找所有元素
- excel - 跨多行汇总合同工时
- java - “spring.cloud.function.scan.packages”是一个未知属性。您的意思是“spring.cloud.function.web.export.auto-startup”吗?