forked from gcallah/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
towers_of_hanoi.rb
96 lines (95 loc) · 2 KB
/
towers_of_hanoi.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
module DivideAndConquer
class << self
@moves = 0
# TODO: Modify the code to output a result for incorporating unit tests
def move_tower(n, source, destination, temporary)
if n > 0
move_tower(n-1, source, temporary, destination)
p "FROM #{source} to #{destination}"
@moves += 1
move_tower(n-1, temporary, destination, source)
end
end
end
end
# Examples:
# move_tower(1, 'A', 'B', 'C') move_tower(6, 'A', 'B', 'C')
# p "Number of moves - #{@moves}" # Number of moves - 63
# # OUTPUT:
# # FROM A to B
# # Number of moves - 1
#
# move_tower(2, 'A', 'B', 'C') move_tower(7, 'A', 'B', 'C')
# p "Number of moves - #{@moves}" # Number of moves - 127
# # OUTPUT:
# # FROM A to C
# # FROM A to B
# # FROM C to B
# # Number of moves - 3
#
# move_tower(3, 'A', 'B', 'C')
# p "Number of moves - #{@moves}"
# # OUTPUT:
# # FROM A to B
# # FROM A to C
# # FROM B to C
# # FROM A to B
# # FROM C to A
# # FROM C to B
# # FROM A to B
# # Number of moves - 7
#
# move_tower(4, 'A', 'B', 'C')
# p "Number of moves - #{@moves}"
# # OUTPUT:
# # FROM A to C
# # FROM A to B
# # FROM C to B
# # FROM A to C
# # FROM B to A
# # FROM B to C
# # FROM A to C
# # FROM A to B
# # FROM C to B
# # FROM C to A
# # FROM B to A
# # FROM C to B
# # FROM A to C
# # FROM A to B
# # FROM C to B
# # Number of moves - 15
#
# move_tower(5, 'A', 'B', 'C')
# p "Number of moves - #{@moves}"
# # FROM A to B
# # FROM A to C
# # FROM B to C
# # FROM A to B
# # FROM C to A
# # FROM C to B
# # FROM A to B
# # FROM A to C
# # FROM B to C
# # FROM B to A
# # FROM C to A
# # FROM B to C
# # FROM A to B
# # FROM A to C
# # FROM B to C
# # FROM A to B
# # FROM C to A
# # FROM C to B
# # FROM A to B
# # FROM C to A
# # FROM B to C
# # FROM B to A
# # FROM C to A
# # FROM C to B
# # FROM A to B
# # FROM A to C
# # FROM B to C
# # FROM A to B
# # FROM C to A
# # FROM C to B
# # FROM A to B
# # Number of moves - 31