Guest User

Untitled

a guest
Jun 24th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. def display
  4. STICKS.each do |stick|
  5. print "|"
  6. stick.each do |ring|
  7. print ring.to_s + " "
  8. end
  9. puts
  10. end
  11. end
  12.  
  13. def valid_move?(from, to)
  14. range = 0..(STICKS.size-1)
  15. return [false, "no-op"] if from == to
  16. return [false, "from should be 0..2"] unless range.cover?(from)
  17. return [false, "to should be 0..2"] unless range.cover?(to)
  18. return [false, "no ring on stick #{from}"] if STICKS[from].size == 0
  19.  
  20. ring = STICKS[from][-1]
  21.  
  22. # Avoid a nil check
  23. return true if STICKS[to].empty?
  24.  
  25. return [false, "invalid move"] if ring > STICKS[to][-1]
  26.  
  27. true
  28. end
  29.  
  30. print "Number of sticks: "
  31. STICKS = gets.to_i.times.map { [] }
  32. puts
  33.  
  34. print "Height of tower: "
  35. STICKS[0] = (1..(gets.to_i)).to_a.reverse
  36. puts
  37.  
  38. loop do
  39. display
  40.  
  41. if STICKS[0].empty? && STICKS[1].empty?
  42. puts "you win!"
  43. exit 0
  44. end
  45.  
  46. print "move: "
  47. from, to = gets.split(" ", 2)
  48. from = from.to_i
  49. to = to.to_i
  50. puts "Move rightmost ring from stick #{from.to_i} to stick #{to.to_i}"
  51.  
  52. valid, error = valid_move?(from, to)
  53. if !valid
  54. puts "Invalid move! #{error}"
  55. next
  56. end
  57.  
  58. STICKS[to].push(STICKS[from].pop)
  59. end
Add Comment
Please, Sign In to add comment