vb.net 如何找到多维数组的最小值和最大值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14631599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the min and max value of a multidimensional array?
提问by djv
I want to find the minimum and maximum values of this array. At some point it is set to (512, 512)UShorts. A For loop would be very time consuming for this many points and am looking for something cleaner. SelectMany occurred to me but I don't know how to implement it.
我想找到这个数组的最小值和最大值。在某些时候,它被设置为(512, 512)UShorts。For 循环对于这么多点来说会非常耗时,并且我正在寻找更清洁的东西。我想到了 SelectMany,但我不知道如何实现它。
Dim usResult As UShort(,)
edit: I have tried
编辑:我试过了
Dim minValue As UShort = UShort.MaxValue
Dim maxValue As UShort = UShort.MinValue
Dim sw As New Stopwatch()
sw.Start()
For i As Integer = 0 To 511 Step 1
For j As Integer = 0 To 511 Step 1
minValue = Math.Min(usResult(i, j), minValue)
maxValue = Math.Max(usResult(i, j), maxValue)
Next
Next
sw.Stop()
Console.WriteLine(sw.ElapsedMilliseconds)
' This takes 2 to 3 milliseconds
采纳答案by xpda
A for loop might be much less time-consuming than you expect. Try timing it to see how long it takes to find the min and max 100,000 times with nested loops.
for 循环可能比您预期的要少得多。尝试计时以查看使用嵌套循环查找最小和最大 100,000 次需要多长时间。
回答by Meta-Knight
The simplest way to get min/max of a multi-dimensional array is by doing this:
获得多维数组的最小值/最大值的最简单方法是这样做:
Dim max As UShort = usResult.Cast(Of UShort).Max()
Dim min As UShort = usResult.Cast(Of UShort).Min()
It doesn't offer better performance than a for loop though. You would need to use a specialized data structure that keeps elements sorted, or keeps track of min/max elements, to get better performance.
尽管如此,它并没有提供比 for 循环更好的性能。您需要使用专门的数据结构来保持元素排序,或跟踪最小/最大元素,以获得更好的性能。

