Last active
December 24, 2015 10:39
-
-
Save ivanbrennan/6785759 to your computer and use it in GitHub Desktop.
Tower of Hanoi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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