Skip to content

Instantly share code, notes, and snippets.

@ivanbrennan
Last active December 24, 2015 10:39
Show Gist options
  • Select an option

  • Save ivanbrennan/6785759 to your computer and use it in GitHub Desktop.

Select an option

Save ivanbrennan/6785759 to your computer and use it in GitHub Desktop.
Tower of Hanoi
# tower_of_hanoi.rb
a = [1,2,3,4]
b = []
c = []
# Move the disks from one peg to another following the rules of Hanoi.
#
# number_of_disks - the total number of disks
# from - the starting peg
# to - the ending (goal) peg
# via - the remaining peg (b in this case)
#
def move_disk(number_of_disks,from,to,via)
if number_of_disks == 1
to.unshift(from.shift)
else
via.unshift(from.shift)
move_disk(number_of_disks-1, from, to, via)
to.unshift(via.shift)
end
to
end
# here we go!
move_disk(4, a, c, b)
[a,b,c].each {|arr| p arr}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment