class Object
Public Instance Methods
towers_of_hanoi()
click to toggle source
# File lib/tower_of_hanoi.rb, line 1 def towers_of_hanoi @hash1 = {"a" => 3, "b" => 2, "c" => 1} @hash2 = {} @hash3 = {} arr = [@hash1, @hash2, @hash3] moves = 0 until @hash3 == {"a" => 3, "b" => 2, "c" => 1} avail = {} puts "CURRENTLY: " p arr # puts visual arr.each {|i| avail.merge!(Hash[*i.max_by {|a,b| b}]) if i != {}} puts "Disks available to move: " puts avail.keys puts "Which disk to move? " move = 'z' move = gets.chomp until (avail.has_key?move) == true arr.each {|i| i.delete(move) if i[move] != nil} avail = [] i = 0 while i < arr.size if arr[i] == {} avail[i] = arr[i] elsif move < arr[i].keys.min avail[i] = arr[i] else avail[i] = nil end i += 1 end puts "Pegs available to move disk to: " puts "LEFT (0)" if avail[0].nil? == false puts "MIDDLE (1)" if avail[1].nil? == false puts "RIGHT (2)" if avail[2].nil? == false puts "Where to place disk? " move2 = 9 move2 = gets.chomp until avail[move2.to_i].nil? == false if arr[move2.to_i].values.empty? v = 1 else v = arr[move2.to_i].values.max + 1 end arr[move2.to_i].merge!(move => v) moves += 1 end return "You Win! In #{moves} moves!" end
visual()
click to toggle source
BROKEN AND INCOMPLETE :/
# File lib/tower_of_hanoi.rb, line 56 def visual disks = {"a" => " _ ", "b" => " ___ ", "c" => "_____", "d" => " "} row3 = ["POSITION3:"] row2 = ["POSITION2:"] row1 = ["POSITION1:"] @hash1 = {"a" => 1, "b" => 2} @hash2 = {"a" => 1, "b" => 2, "c" => 3} @hash3 = {"a" => 1,} board = [@hash1, @hash2, @hash3] board.each_with_index do |hsh, idx| n = 4 (3-hsh.size).times do hsh.merge!(n => n) n += 1 end puts hsh hsh.each do |k,v| # eval(x = "row" + v.to_s "\n" x = disks[k] if v < 4) # if v > 3 # row3[1] = disks["d"] if v.index?() # row2[1] = disks["d"] # row1[1] = disks["d"] # else # row3[idx+1] = disks[k] if v == 3 # row2[idx+1] = disks[k] if v == 2 # row1[idx+1] = disks[k] if v == 1 # end end (hsh.size).times do n -= 1 hsh.delete(n) end end puts " " + " SLOT0" + " SLOT1" + " SLOT2" puts row3.join(" ") puts row2.join(" ") puts row1.join(" ") end