书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第8章目录
8.3 用递归函数实现康托尔集
接下来,我们要用递归函数实现康托尔集的可视化。从哪里开始?
void cantor(float x, float y, float len) {
line(x,y,x+len,y);
}
从康托尔规则中可以看出,我们需要去掉线段中间的1/3,剩下两条线段:一条线段从起点到1/3处,另一个条线段从2/3处到终点。
我们要分别绘制这两条线段。我们沿y轴方向将这两条线段下移几个像素,让它们显示在原线段的下方。
void cantor(float x, float y, float len) {
line(x,y,x+len,y);
y += 20;
line(x,y,x+len/3,y); 从起点到1/3处
line(x+len*2/3,y,x+len,y); 从2/3处到终点
}
void cantor(float x, float y, float len) {
line(x,y,x+len,y);
y += 20;
cantor(x,y,len/3);
cantor(x+len*2/3,y,len/3);
}
示例代码8-4 康托尔集
void setup() {
size(800, 200);
background(255);
// Call the recursive function
cantor(35, 0, 730);
}
void draw() {
// No need to loop
noLoop();
}
void cantor(float x, float y, float len) {
float h = 30;
// recursive exit condition
if (len >= 1) {
// Draw line (as rectangle to make it easier to see)
noStroke();
fill(0);
rect(x, y, len, h/3);
// Go down to next y position
y += h;
// Draw 2 more lines 1/3rd the length (without the middle section)
cantor(x, y, len/3);
cantor(x+len*2/3, y, len/3);
}
}