# 递归和递归定义的几何对象

2019年 7月 17日

### Sierpinski 地毯

```if (level < 1)
error("Carpet level needs to be at least 1.");
if (level > 5)
error("Carpet level needs to be at most 5.");

counter = 0;
model.component("comp1").geom("geom1").feature().clear();
model.component("comp1").geom("geom1").autoRebuild("off");
double cx0 = 0, cy0 = 0;
double si0 = 1;
carpet(level, cx0, cy0, si0);
model.component("comp1").geom("geom1").runPre("fin");
```

```int l = level;
double posx, posy, si1;
String strix;
int l1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
posx = cx+i*si-si;
posy = cy+j*si-si;
strix = toString(i)+toString(j);
if ((Math.abs((i-1))+Math.abs((j-1))) > 0) {
if (l == 1) {
counter = counter+1;
model.component("comp1").geom("geom1").create("sq"+strix+"C"+toString(counter), "Square");
with(model.component("comp1").geom("geom1").feature("sq"+strix+"C"+toString(counter)));
set("base", "center");
set("size", new double[]{si});
set("pos", new double[]{posx, posy});
endwith();
model.component("comp1").geom("geom1").feature("sq"+strix+"C"+toString(counter)).label("Square"+strix+"C"+toString(counter));
} else {
l1 = l-1;
si1 = si/3;
carpet(l1, posx, posy, si1);
}
}
}
}
```

### Menger海绵

```if (level < 1)
error("Carpet level needs to be at least 1.");
if (level > 5)
error("Carpet level needs to be at most 5.");

counter = 0;
model.component("comp1").geom("geom1").feature().clear();
model.component("comp1").geom("geom1").autoRebuild("off");
double cx0 = 0, cy0 = 0;
double si0 = 1;
carpet(level, cx0, cy0, si0);
model.component("comp1").geom("geom1").runPre("fin");
```

```int l = level;
double posx, posy, si1;
String strix;
int l1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
posx = cx+i*si-si;
posy = cy+j*si-si;
strix = toString(i)+toString(j);
if ((Math.abs((i-1))+Math.abs((j-1))) > 0) {
if (l == 1) {
counter = counter+1;
model.component("comp1").geom("geom1").create("sq"+strix+"C"+toString(counter), "Square");
with(model.component("comp1").geom("geom1").feature("sq"+strix+"C"+toString(counter)));
set("base", "center");
set("size", new double[]{si});
set("pos", new double[]{posx, posy});
endwith();
model.component("comp1").geom("geom1").feature("sq"+strix+"C"+toString(counter)).label("Square"+strix+"C"+toString(counter));
} else {
l1 = l-1;
si1 = si/3;
carpet(l1, posx, posy, si1);
}
}
}
}
```