Last active
September 22, 2020 08:13
-
-
Save vlad-bezden/f5be3862b51935334f83 to your computer and use it in GitHub Desktop.
Solution of Tower of Hanoi problem using F#
This file contains 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
let rec TowerOfHanoi fromPole destPole tempPole disks = | |
if disks > 0 then | |
TowerOfHanoi fromPole tempPole destPole (disks - 1) | |
printfn "Moving from %c to %c" fromPole destPole | |
TowerOfHanoi tempPole destPole fromPole (disks - 1) | |
TowerOfHanoi '1' '2' '3' '4' |
Great write-up! Solution is a lot more readable than some of the other F# solutions out there.
A small correction: printf
in line 4 should be printfn
.
Thank you @isocolon I updated code as you suggested.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tower Of Hanoi Problem using F
The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. We are given a tower of eight disks (initially four in the applet below), initially stacked in increasing size on one of three pegs. The objective is to transfer the entire tower to one of the other pegs (the rightmost one in the applet below), moving only one disk at a time and never a larger one onto a smaller.
Recursive solution
Let call the three pegs Src (Source), Aux (Auxiliary) and Dst (Destination). To better understand and appreciate the following solution you should try solving the puzzle for small number of disks, say, 2,3, and, perhaps, 4. However one solves the problem, sooner or later the bottom disk will have to be moved from Src to Dst. At this point in time all the remaining disks will have to be stacked in decreasing size order on Aux. After moving the bottom disk from Src to Dst these disks will have to be moved from Aux to Dst. Therefore, for a given number N of disks, the problem appears to be solved if we know how to accomplish the following tasks:
Assume there is a function Solve with four arguments - number of disks and three pegs (source, intermediary and destination - in this order). Then the body of the function might look like
Output
More information about this problem can be found at:
Tower of Hanoi
Tower of Hanoi