[問題] 河內塔的演算法
這問題不知道在這邊問妥不妥當
如果不適合的話請跟我說
我會把他刪掉
以下是我寫的河內塔程式
可以將每個碟子移動的過程畫出來方便觀察
演算法是參考網路上很多的範例所寫的
可是我對於各碟子移動的規則
還是看不出一個所以然來
是否有人可以幫我解釋一下
或是網路上有更詳細說明可以與我分享
$src = Array.new
$tmp = Array.new
$des = Array.new
$disk = 3
# 組合出橫向的線
def draw_line(q, index, height)
_rc = ''
i = index - (height - q.size)
if(i<0)
_rc << ' '*(height-1) << "||" << ' '*(height-1)
else
_rc << ' '*(height-q[i]) << "=="*(q[i]) << ' '*(height-q[i])
end
return _rc
end
# 畫出目前的狀態
def pirnt_queue
puts ''
_tower_height = $disk+1
0.upto(_tower_height-1) do |i|
_line = ''
_line << draw_line($src, i, _tower_height)
_line << draw_line($tmp, i, _tower_height)
_line << draw_line($des, i, _tower_height)
puts _line
end
end
# 移動最上面的碟子
def move_top(q_src, q_des)
q_des.insert(0, q_src[0])
q_src.delete_at(0)
pirnt_queue
end
def honai(n, q_src, q_tmp, q_des)
if(n==1)
move_top(q_src, q_des)
return
end
honai(n-1, q_src, q_des, q_tmp)
move_top(q_src, q_des)
honai(n-1, q_tmp, q_src, q_des)
end
def hand_made
move_top($src, $des)
move_top($src, $tmp)
move_top($des, $tmp)
move_top($src, $des)
move_top($tmp, $src)
move_top($tmp, $des)
move_top($src, $des)
end
def main
1.upto($disk){|i|$src.push(i)}
pirnt_queue
#hand_made
honai($disk, $src, $tmp, $des)
end
if($1==$FILE)
main
end
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.220.71.34
推
09/20 14:15, , 1F
09/20 14:15, 1F
→
09/20 14:16, , 2F
09/20 14:16, 2F
推
09/20 15:47, , 3F
09/20 15:47, 3F
推
09/22 11:44, , 4F
09/22 11:44, 4F
→
09/22 11:45, , 5F
09/22 11:45, 5F
→
09/22 11:45, , 6F
09/22 11:45, 6F
→
09/22 11:46, , 7F
09/22 11:46, 7F
→
09/22 11:46, , 8F
09/22 11:46, 8F
→
09/22 11:47, , 9F
09/22 11:47, 9F
→
09/22 11:47, , 10F
09/22 11:47, 10F
→
09/22 11:47, , 11F
09/22 11:47, 11F
→
09/22 11:48, , 12F
09/22 11:48, 12F
→
09/23 09:36, , 13F
09/23 09:36, 13F
→
09/24 02:35, , 14F
09/24 02:35, 14F
→
09/27 01:20, , 15F
09/27 01:20, 15F
討論串 (同標題文章)
Ruby 近期熱門文章
PTT數位生活區 即時熱門文章