moshkit

hanoi

Apr 25th, 2020
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. $n = 11
  2. $towers = {}
  3. $idx = {a: 1, b: 2, c: 3}
  4. ​
  5. def init
  6. $towers = {
  7. a: 1.upto($n).to_a.reverse,
  8. b: [],
  9. c: []
  10. }
  11. end
  12.  
  13. ​init()
  14.  
  15. ​def stat()
  16. ts = [:a, :b, :c]
  17. puts ts.join("\t")
  18. ($n - 1).downto(0).each do |i|
  19. [:a, :b, :c].each do |t|
  20. print "#{$towers[t][i]}\t"
  21. end
  22. puts
  23. end
  24. end
  25.  
  26. ​def m(from, to)
  27. d = $towers[from].pop
  28. dest_d = $towers[to].last
  29. if (to == :b && d == 1) || (dest_d && d > dest_d)
  30. puts("illegal move")
  31. exit(0)
  32. end
  33. $towers[to].push(d)
  34. puts "#{d} #{$idx[from]} #{$idx[to]}"
  35. end
  36.  
  37. ​
  38.  
  39. ​
  40.  
  41. def move_right
  42. m(:a,:c)
  43. m(:a,:b)
  44. m(:c,:a)
  45. m(:b,:c)
  46. m(:a,:c)
  47. end
  48.  
  49. ​
  50.  
  51. def move_left
  52. m(:c,:a)
  53. m(:c,:b)
  54. m(:a,:c)
  55. m(:b,:a)
  56. m(:c,:a)
  57. end
  58.  
  59. ​
  60.  
  61. def swap()
  62. da = $towers[:a].last.to_i
  63. db = $towers[:b].last.to_i
  64. dc = $towers[:c].last.to_i
  65.  
  66. ts = [da, db, dc]
  67. idx = [:a, :b, :c]
  68.  
  69. ​ ts.each_with_index do |d, i|
  70. next if d == 0 || d == 1
  71. ts.each_with_index do |dd, ii|
  72. next if dd == d
  73. ​
  74. if dd == 0 || d < dd
  75. return [idx[i], idx[ii]]
  76. end
  77. end
  78. end
  79. end
  80.  
  81. def done?()
  82. $towers[:a].last == nil && $towers[:b].last == nil
  83. end
  84.  
  85. ​
  86. def solve
  87. while true
  88. move_right
  89. break if done?()
  90. m(*swap())
  91. move_left
  92. m(*swap())
  93. end
  94. end
  95.  
  96. stat()
  97. solve()
  98. stat()
Advertisement
Add Comment
Please, Sign In to add comment