powershell 汉洛塔

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shrekz/article/details/50263875
#powershell 汉洛塔
#可变长数组Collections.ArrayList操作
#递归函数
#文字排版和配色
function hanoi($n)
{
$global:num=0
$global:arraya=New-Object Collections.ArrayList
$global:arrayb=New-Object Collections.ArrayList
$global:arrayc=New-Object Collections.ArrayList
$global:arraya.addrange(1..$n)
Write-Host $("初始状态:").PadLeft(13) -NoNewline
Write-Host ($global:arraya -join ",").PadRight(9) -NoNewline
Write-Host ($global:arrayb -join ",").PadRight(9) -NoNewline
Write-Host ($global:arrayc -join ",").PadRight(9)
function go($n,$a,$b,$c)
{ 
    if($n -eq 1)
        {   
        $global:num++
        if($a -eq "a" -and $c -eq "b"){$s1="a";$a1="-->     ";$s2="b  ";$a2="";$s3=""
        $global:arrayb.Insert(0,$global:arraya[0])
        $global:arraya.Removeat(0)
        }
        if($a -eq "a" -and $c -eq "c"){$s1="a";$a1="";$s2="---->";$a2="";$s3="c"
        $global:arrayc.Insert(0,$global:arraya[0])
        $global:arraya.Removeat(0)            
        }
        if($a -eq "b" -and $c -eq "a"){$s1="a";$a1="<--     ";$s2="b  ";$a2="";$s3=""
        $global:arraya.Insert(0,$global:arrayb[0])
        $global:arrayb.Removeat(0)            
        }
        if($a -eq "b" -and $c -eq "c"){$s1=" ";$a1="";$s2="b  ";$a2="-->";$s3="c"
        $global:arrayc.Insert(0,$global:arrayb[0])
        $global:arrayb.Removeat(0)            
        }
        if($a -eq "c" -and $c -eq "a"){$s1="a";$a1="";$s2="<----";$a2="";$s3="c"
        $global:arraya.Insert(0,$global:arrayc[0])
        $global:arrayc.Removeat(0)           
        }
        if($a -eq "c" -and $c -eq "b"){$s1=" ";$a1="";$s2="b  ";$a2="<--";$s3="c"
        $global:arrayb.Insert(0,$global:arrayc[0])
        $global:arrayc.Removeat(0)      
        }  
        Write-Host $("第$num`步:").PadLeft(15) -NoNewline
        Write-Host "$($s1)" -ForegroundColor 3 -NoNewline -BackgroundColor 15
        Write-Host "$($a1.PadLeft(17))" -ForegroundColor 1 -NoNewline -BackgroundColor 15
        Write-Host "$($s2.PadRight(12))" -ForegroundColor 9 -NoNewline -BackgroundColor 15
        Write-Host "$($a2.PadLeft(6))" -ForegroundColor 1 -NoNewline -BackgroundColor 15
        Write-Host "$($s3.PadLeft(12))" -ForegroundColor 12 -BackgroundColor 15
        Write-Host $("当前状态:").PadLeft(13) -NoNewline
        Write-Host ($global:arraya -join ",").PadRight(18) -NoNewline
        Write-Host ($global:arrayb -join ",").PadRight(12) -NoNewline
        Write-Host ($global:arrayc -join ",").PadLeft(18)
        }
    else
        {
        go ($n-1) $a $c $b
        go 1 $a $b $c
        go ($n-1) $b $a $c
        }

    }
go $n "a" "b" "c"
}

hanoi 4

猜你喜欢

转载自blog.csdn.net/shrekz/article/details/50263875