SHARE
TWEET

hanoi

moshkit Apr 25th, 2020 605 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. $n = 11
  4.  
  5.  
  6. $towers = {}
  7.  
  8.  
  9. $idx = {a: 1, b: 2, c: 3}
  10.  
  11.  
  12. def init
  13.  
  14.   $towers = {
  15.  
  16.     a: 1.upto($n).to_a.reverse,
  17.  
  18.     b: [],
  19.  
  20.     c: []
  21.  
  22.   }
  23.  
  24. end
  25.  
  26.  
  27. init()
  28.  
  29.  
  30. def stat()
  31.  
  32.   ts = [:a, :b, :c]
  33.  
  34.   puts ts.join("\t")
  35.  
  36.   ($n - 1).downto(0).each do |i|
  37.  
  38.     [:a, :b, :c].each do |t|
  39.  
  40.       print "#{$towers[t][i]}\t"
  41.  
  42.     end
  43.  
  44.     puts
  45.  
  46.   end
  47.  
  48. end
  49.  
  50.  
  51. def m(from, to)
  52.  
  53.   d = $towers[from].pop
  54.  
  55.   dest_d = $towers[to].last
  56.  
  57.   if (to == :b && d == 1) || (dest_d && d > dest_d)
  58.  
  59.     puts("illegal move")
  60.  
  61.     exit(0)
  62.  
  63.   end
  64.  
  65.   $towers[to].push(d)
  66.  
  67.   puts "#{d} #{$idx[from]} #{$idx[to]}"
  68.  
  69. end
  70.  
  71.  
  72.  
  73. def move_right
  74.  
  75.   m(:a,:c)
  76.  
  77.   m(:a,:b)
  78.  
  79.   m(:c,:a)
  80.  
  81.   m(:b,:c)
  82.  
  83.   m(:a,:c)
  84.  
  85. end
  86.  
  87.  
  88. def move_left
  89.  
  90.   m(:c,:a)
  91.  
  92.   m(:c,:b)
  93.  
  94.   m(:a,:c)
  95.  
  96.   m(:b,:a)
  97.  
  98.   m(:c,:a)
  99.  
  100. end
  101.  
  102.  
  103. def swap()
  104.  
  105.   da = $towers[:a].last.to_i
  106.  
  107.   db = $towers[:b].last.to_i
  108.  
  109.   dc = $towers[:c].last.to_i
  110.  
  111.  
  112.   ts = [da, db, dc]
  113.  
  114.  
  115.   idx = [:a, :b, :c]
  116.  
  117.  
  118.   ts.each_with_index do |d, i|
  119.  
  120.     next if d == 0 || d == 1
  121.  
  122.  
  123.     ts.each_with_index do |dd, ii|
  124.  
  125.       next if dd == d
  126.  
  127.  
  128.       if dd == 0 || d < dd
  129.  
  130.         return [idx[i], idx[ii]]
  131.  
  132.       end
  133.  
  134.     end
  135.  
  136.   end
  137.  
  138. end
  139.  
  140.  
  141.  
  142. def done?()
  143.  
  144.   $towers[:a].last == nil && $towers[:b].last == nil
  145.  
  146. end
  147.  
  148.  
  149. def solve
  150.  
  151.   while true
  152.  
  153.     move_right
  154.  
  155.     break if done?()
  156.  
  157.     m(*swap())
  158.  
  159.     move_left
  160.  
  161.     m(*swap())
  162.  
  163.   end
  164.  
  165. end
  166.  
  167.  
  168. stat()
  169.  
  170. solve()
  171.  
  172. stat()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top