Get minimum value in an array and then get index

江枫思渺然 提交于 2019-12-12 02:12:29

问题


I want to get the minimum value in an array and then get the index of that item, in one step without writing my own loop (if I have to please let me know).

I know I can just do the
$b = ($a | Measure -Minimum).Minimum
But then I have to do
[array]::IndexOf($a, $b)
And while that is normally okay, I'm looking for a way to do it once because I'm running this MANY MANY times in a loop.

Thanks!

EDIT: One step meaning without looping through the array twice


回答1:


Personally, I might consider a different data structure. Maybe something sorted to begin with...

This code may work for your needs:

$myArray = 5,66,4,33,2,9,9,12


$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }

"MinIndex $minIndex = MinValue $minValue"



回答2:


its a problem of type, try like this:

$myArray = [int[]]5,66,4,33,2,9,9,12
$minvalue=[int]($myArray | measure -Minimum).Minimum
$myArray.IndexOf($minvalue)


来源:https://stackoverflow.com/questions/42033959/get-minimum-value-in-an-array-and-then-get-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!