代码之家  ›  专栏  ›  技术社区  ›  Francesco Mantovani

打印序列中缺少的数字

  •  -2
  • Francesco Mantovani  · 技术社区  · 8 年前

    我有个文件叫 test.txt 其中我有一个序列:

    1
    3
    5
    6
    7
    

    magic code

    gc test.txt |% {$i = 1}{while ($i -lt $_){$i;$i++};$i++}
    

    或者这个:

    gc test.txt | sort {[int]$_} |% {$i = 1}{while ($i -lt $_){$i;$i++};$i++}
    

    但我想打印 全部 数字:

    • 在 绿色 列表中的数字
    • 在 列表中缺少的数字
    2 回复  |  直到 8 年前
        1
  •  4
  •   TheMadTechnician    8 年前

    读取文件,从第一个数字开始,最后一个数字结束,然后输出文件中没有的任何数字。。。

    $TestFile = Get-Content Test.txt|Sort
    [int]$TestFile[0]..[int]$TestFile[-1]|Where{$_ -notin $TestFile}
    

    编辑:

    $TestFile = Get-Content Test.txt|Sort
    Switch([int]$TestFile[0]..[int]$TestFile[-1]){
        {$_ -notin $TestFile}{Write-Host "$_" -Fore Red;Continue}
       default {Write-Host "$_" -Fore Green}
    }
    
        2
  •  1
  •   user6811411 user6811411    8 年前

    只需插入 Write-Host -Fore red/green 在正确的地方:

    gc test.txt | % {$i = 1}{while ($i -lt $_){write-host -Fore red $i;$i++};write-host -Fore green $i;$i++}
    

    没有别名时相同:

    Get-Content .\test.txt | ForEach-Object {$i = 1}{
       while ($i -lt $_){
         Write-Host -ForegroundColor Red $i
         $i++
       }
       Write-Host -ForegroundColor Green $i
       $i++
     }
    

    enter image description here