We build an inverted triangle pattern involving the specified number of equilateral triangles. We are given the initial size of the first triangle. Successive triangles have sides which are half the length of the surrounding triangle. Successive triangles are inverted and placed inside the surrounding triangle to touch it at three points.
If the number of triangles is less than 1, do nothing.
invertTriangles(2) = equiTriangle + invertTriangles(1, inverted
and size shrunk by half)
invertTriangles(3) = equiTriangle + invertTriangles(2, inverted and
size shrunk by half)
invertTriangles(4) = equiTriangle + invertTriangles(3, inverted and
size shrunk by half)
where equiTriangle is a method that will draw an equilateral
triangle.
There are lots of possible solutions here. One thing we can do is to move half the size forward and then turn left 60 degrees.
Invariant: We need to start and end the pattern in the same
place.
If we move to the next position in the way specified above, we need
to turn right 60 degrees and move half the size backward to get back
to the starting position.
We assume we have methods (defined below) which answer each of the questions above.
public void invertTriangles (double size, int number) { System.out.println("invertTriangles("+size+", "+number+");"); if (number>0) { // base case equiTriangle(size); // draw the outer triangle moveToNextTriangle(size/2); // move in position to draw the next triangle pattern invertTriangles(size/2, number-1); // draw next pattern returnToStart(size/2); // meet invariant: start and end in same place } }
// draws an equilateral triangle with sides of the specified size public void equiTriangle (double size) { System.out.println("equiTriangle size "+size); fd(size); lt(120); fd(size); lt(120); fd(size); lt(120); }
public void moveToNextTriangle (double distance) { System.out.println("moveToNextTriangle"); fd(distance); lt(60); }
public void returnToStart (double distance) { System.out.println("returnToStart"); rt(60); bd(distance); }