Skip to content

Commit d375945

Browse files
authored
Create hanoi.jl
1 parent a4afe1b commit d375945

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

hanoi.jl

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
2+
# coding: utf-8
3+
4+
# In[1]:
5+
6+
7+
#hanoi tower is the classic recursion
8+
#the logic behind it is amazing
9+
#rules can be seen from this website:
10+
# https://en.wikipedia.org/wiki/Tower_of_Hanoi
11+
12+
13+
# In[2]:
14+
15+
16+
function hanoi(n,column1,column2,column3)
17+
18+
#rule states that each time we can only move one element
19+
#so when the recursion reaches to base case 1
20+
#we print the movement of elements from column 1 to column 3
21+
if n==1
22+
println(column1," -> ",column3)
23+
return
24+
end
25+
26+
#for the general case
27+
#the first step is to move everything above the base case from column 1 to column 2
28+
#note that we set print 1 to 3 when n reaches one
29+
#so in this case we reorder the function, replace column 3 with column 2
30+
#where elements actually move towards
31+
#the reorder is purely for printing
32+
hanoi(n-1,column1,column3,column2)
33+
34+
#the second step is to move the base case from column 1 to column 3
35+
#we are only moving base case, thats why n=1
36+
hanoi(1,column1,column2,column3)
37+
38+
#final step would be move everything above base case from column 2 to column 3
39+
hanoi(n-1,column2,column1,column3)
40+
41+
end
42+
43+
44+
# In[3]:
45+
46+
47+
#the best explanation should be
48+
# https://www.python-course.eu/towers_of_hanoi.php
49+
50+
51+
# In[4]:
52+
53+
54+
hanoi(4,"Column A","Column B","Column C")
55+

0 commit comments

Comments
 (0)