Hanoi
Haskellでハノイの塔を解く。
書籍、「C言語によるはじめてのアルゴリズム入門」の内容をそのまま落とし込みました
type Disk = Int type Disks = (Int,[Disk]) type Pillar = [Disks] hanoi :: Int -> Pillar ->IO() hanoi 0 _ = return () hanoi n [(a,p1),(b,p2),(c,p3)] = do hanoi (n-1) [(a,p1),(c,p3),(b,p2)] print str hanoi (n-1) [(c,p3),(b,p2),(a,p1)] where str = show n++"was moved from "++show a++" to "++show b dataSet :: Int -> Pillar dataSet n = zip [1..3] $ take n [1..] : [[0],[0]] main = do n <- getLine hanoi (read n).dataSet $ read n
はじめにあるtype宣言は、円盤の大きさから柱の状態を表すためのもの
実行結果は以下のよう
$>hanoi 3 "1was moved from 1 to 2" "2was moved from 1 to 3" "1was moved from 2 to 3" "3was moved from 1 to 2" "1was moved from 3 to 1" "2was moved from 3 to 2" "1was moved from 1 to 2"
ただこれでは寂しいので、ちゃんと遷移の様子が分かるようにしたいのだけれど...