我希望获得数组中的最小值,然后获取该项的索引,只需一步即可编写自己的循环(如果我必须让我知道)。
我知道我可以做到
$b = ($a | Measure -Minimum).Minimum
但后来我必须做
[array]::IndexOf($a, $b)
虽然这通常没问题,但我正在寻找一种方法,因为我在循环中运行了很多次。
谢谢!
编辑:一步意味着没有循环数组两次
答案 0 :(得分:1)
就个人而言,我可能会考虑不同的数据结构。也许有些事情要从......开始......
此代码可能适合您的需求:
$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"
答案 1 :(得分:1)
它的类型问题,请尝试这样:
$myArray = [int[]]5,66,4,33,2,9,9,12
$minvalue=[int]($myArray | measure -Minimum).Minimum
$myArray.IndexOf($minvalue)
答案 2 :(得分:0)
这里有6种不同的选择供您选择...
cls
$myArray = @(5,66,4,33,2,9,9,12)
$iterations = 50000
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minValue = [int]($myArray | Measure-Object -Minimum).Minimum
$minIndex = $myArray.IndexOf($minValue)
}
}).TotalSeconds
"measure-object with indexOf: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }
}
}).TotalSeconds
"pipeline with compare: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = 0
$minValue = [int]::MaxValue
foreach ($index in 0..($myArray.count-1)) {
if ($myArray[$index] -lt $minValue) {
$minValue = $myArray[$index]
$minIndex = $index
}
}
}
}).TotalSeconds
"foreach-loop with compare: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$h = [System.Collections.ArrayList]::new()
foreach ($index in 0..($myArray.count-1)) {
$null = $h.add([tuple]::Create($myArray[$index], $index))
}
$h.Sort()
$minIndex = $h[0].Item2
}
}).TotalSeconds
"quicksort of a list of tuples: $t"
Add-Type -TypeDefinition @"
using System;
using System.Linq;
public static class My {
public static int indexOfMin(int[] arr){
int min = arr.Min();
return Array.IndexOf(arr, min);
}
}
"@
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = [my]::indexOfMin($myArray)
}
}).TotalSeconds
"custom type and IndexOf: $t"
Add-Type -TypeDefinition @"
using System;
using System.Linq;
public static class My2 {
public static int indexOfMin(int[] arr){
int min = int.MaxValue;
int minIndex = 0;
for (int i = 0; i < arr.Length; i++) {
if (arr[i]<min) {
min = arr[i];
minIndex = i;
}
}
return minIndex;
}
}
"@
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = [my2]::indexOfMin($myArray)
}
}).TotalSeconds
"custom type and looping: $t"