arrays - 在Powershell数组中查找最接近的数值

标签 arrays powershell-2.0 windows-7-x64

问:我正在寻找一种更优雅的方法来从数组中获取数字的最接近匹配项。
我这里的事情可能太复杂了

输入项

## A given array A where to search in
$a = (16/10),(16/9),(4/3),(5/4),(21/10),(21/9)  

## A given value B which should be searched for in array A (closest match)
$b = 16/11

所需的输出
"Closest value to 16/11 is 4/3"

我目前的代码可以解决问题
## New array C for the differences of array A - B
$c = $a | %{  [math]::abs($_ - $b) } 

## Measure array C to get lowest value D
$d = $c | measure -Minimum

## Get position E of value D in array C
$e = [array]::IndexOf($c, $d.minimum)

## Position E correlates to array A
echo "Closest value to $b is $($a[$e])

备注
  • 如果哈希表或其他更合适的
  • ,则不必是数组
  • 我当前的代码输出类似于1.33333的小数而不是分数4/3。输出分数
  • 会很好
  • 短代码总是更好
  • 最佳答案

    $a = (16/10),(16/9),(4/3),(5/4),(21/10),(21/9) 
    $b = 16/11
    $oldval = $b - $a[0]
    $Final = $a[0]
    if($oldval -lt 0){$oldval = $oldval * -1}
    $a | %{$val = $b - $_
    if($val -lt 0 ){$val = $val * -1}
    if ($val -lt $oldval){
    $oldval = $val
    $Final = $_} }
    Write-host "$Final is the closest to $b"
    

    关于arrays - 在Powershell数组中查找最接近的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27421847/

    相关文章:

    Javascript - 数组覆盖

    用于从文件夹列表中省略遍历访问被拒绝的文件夹的 Powershell 脚本

    powershell - 在PowerShell中使用全局变量的最佳方法?

    windows - 在 Windows 7 上使用 PowerShell 从 COM 端口捕获输出

    javascript - 通过键名从对象数组中删除重复的对象

    Javascript 附加对象不保证顺序

    hadoop - 用于 Hadoop 开发的 Eclipse 设置

    java - 为什么 JDK1.8.0u121 无法找到 kerberos default_tkt_enctypes 类型? (KrbException : no supported default etypes for default_tkt_enctypes)

    ole32 崩溃!COIDTable::ThreadCleanup ...NetworkItemFactory!FDBackgroundThreadHandler

    arrays - 通过 Postman 发送 JSON 会导致我的 Node.js 服务出现错误