您的位置:首页 > 运维架构 > Shell

powershell 汉洛塔

2015-12-11 14:59 495 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: