作業八: hanoi tower
•建立一個 shell 執行檔, 名為 hanoi, 可印出 hanoi tower problem 中 disc 移動的順序
$ ./hanoi 2 # move 2 discs, from A to B by C from A to C from A to B from C to B $ ./hanoi 3 # move 3 discs, from A to B by C from A to B from A to C from B to C from A to B from C to A from C to B from A to B $
解答:
#!/bin/bash
function move_disc {
if [ $1 -ne 0 ]; then
move_disc $(($1-1)) $2 $4 $3
echo from $2 "to" $3
move_disc $(($1-1)) $4 $3 $2
fi
}
#-----Main Program-----
disc=$1
if [ $disc -gt 0 ]; then
move_disc $disc A B C
fi
執行結果:
沒有留言:
張貼留言