-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrecursion.cpp
148 lines (128 loc) Β· 3 KB
/
recursion.cpp
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include "engine.h"
class RecursiveNumbers : public Engine
{
void setup()
{
createCanvas(60,10);
branch(128, 30, 0);
}
void branch(int n, int x, int y)
{
if (n > 2)
{
text(to_string(n), x, y);
branch(n/2, x + n/8, y + 1);
branch(n/2, x - n/8, y + 1);
}
}
};
class RecursiveTrees : public Engine
{
void setup()
{
createCanvas(50, 20);
branch(25, 0, 30);
}
void branch(int x, int y, int size)
{
if (size > 2)
{
int x1 = x - size * 0.4;
int x2 = x + size * 0.4;
horizontal_line(y, x1, x2);
vertical_line(x1, y+1, y+3);
vertical_line(x2, y+1, y+3);
redraw();
sleep(200);
branch(x1, y+4, size/2);
branch(x2, y+4, size/2);
}
}
};
class RecursiveBlocks : public Engine
{
void setup()
{
createCanvas(50, 33);
stroke("π ");
branch(0, 0, 32, 0);
}
void branch(int x, int y, int size, int levels)
{
if (levels <4)
{
rect(x, y, size, size);
int x1 = x + 1;
int x2 = x + size/2;
int y1 = y + 1;
int y2 = y + size/2;
int s = size/2-1;
stroke("π»");
branch(x1, y1, s, levels+1);
stroke("π²");
branch(x2, y1, s, levels+1);
stroke("πΉ");
branch(x1, y2, s, levels+1);
stroke("π΄");
branch(x2, y2, s, levels+1);
}
}
// void draw()
// {
// stroke("π ");
// branch(0, 0, 32, 0);
// }
};
class Fibonacci : public Engine
{
void setup()
{
createCanvas(35, 10);
fv(6,20,0);
redraw();
noLoop();
}
int f(int n)
{
if (n == 1 || n == 0)
{
return n;
}
else
{
return f(n - 1) + f(n - 2);
}
}
int fv(int n, int x, int y)
{
if (n == 1 || n == 0)
{
text("f(" + to_string(n) + ")=1", x, y);
redraw();
sleep(300);
return n;
}
else
{
stroke("ββ");
horizontal_line(y+1, x - 4, x + 4);
stroke("ββ΄");
point(x, y+1);
int v = fv(n - 1, x - 4, y + 1) + fv(n - 2, x + 4, y + 1);
text("f(" + to_string(n) + ")=" + to_string(v), x, y);
redraw();
sleep(300);
return v;
}
}
};
int main()
{
Menu menu;
menu.add(new RecursiveNumbers(), "Numbers");
menu.add(new RecursiveTrees(), "Trees");
menu.add(new RecursiveBlocks(), "Blocks");
menu.add(new Fibonacci(), "Fibonacci");
menu.play();
return 0;
}