hakeの日記

Windows環境でプログラミングの勉強をしています。

ハノイの塔

再帰プログラムの復習
左の棒に積まれたn個の石板を右の棒へ移動させる。最初は実現方法に戸惑ったけれども、要は一番下の石板と、その上のn-1個の石板のかたまりの2個を操作させると考えればわかりやすい。

  1. n-1個のかたまりを左から中央へ
  2. n(一番下の石板)を左から右へ
  3. n-1個のかたまりを中央から右へ
def hanoi(n,src,tmp,dst) # n個の石板をsrcからdstへ移動
  if n == 1
    puts("move #{n}-disc from #{src} to #{dst}")
  else
    hanoi(n-1,src,dst,tmp) # n-1個の石板をsrcからtmpへ移動
    puts("move #{n}-disc from #{src} to #{dst}")
    hanoi(n-1,tmp,src,dst) # n-1個の石板をtmpからdstへ移動
  end
end


cnt = ARGV[0].to_i
hanoi(cnt,"Left","Center","Right")


石板3枚の場合の実行結果

D:\ruby>ruby hanoi.rb 3
move 1-disc from Left to Right
move 2-disc from Left to Center
move 1-disc from Right to Center
move 3-disc from Left to Right
move 1-disc from Center to Left
move 2-disc from Center to Right
move 1-disc from Left to Right