Algorithm 12.5.1. Nested squares.
Draw a square.
If more divisions are desired
draw a smaller version of pattern within square.
Draw a square.
If more divisions are desired
draw a smaller version of pattern within square.
Draw a square.
If the level is greater than 0,
draw a smaller version of pattern within square.
Graphics
parameter so the method can use the drawRect()
method to draw the square. As we decided, the level
parameter controls the recursion. Note that its value is decreased by 1 in the recursive call. This will ensure that level
will eventually reach 0, and recursion will stop.delta
parameter, which is used to change the length of the sides by a fixed amount, 2 * delta
, at each level. It is also used to calculate the x- and y-coordinates for the location of the next level of boxes (locX + delta, locY + delta). But delta
’s value remains constant through all the levels. This will lead to a pattern where the “gap” between nested squares is constant.drawBoxes()
method with a simple GUI to draw a level-9 picture of the nested boxes.level
variable and re-run the program to draw different levels of the boxes.Base case: Draw a triangle.
Recursive Case: If more divisions are desired,
draw three smaller gaskets within the triangle.
level
parameter to control the depth of the recursion. The higher the level, the more divisions will be drawn.level
parameter as the recursion parameter for this method, which controls the recursion. Note that each of the three recursive calls decreases the level
by 1. This will ensure that eventually level
will equal 0, and recursion will stop.(p1X,p1Y)
to (p2X,p2Y)
, from (p2X,p2Y)
to (p3X,p3Y)
, and from (p3X,p3Y)
back to (p1X, p1Y)
.(p1X,p1Y)
, and the midpoints of the other two lines from (p1X,p1Y)
to (p2X,p2Y)
and from (p1X,p1Y)
to (p3X,p3Y)
. As you might remember from high school math, the formula for computing the midpoint of the line segment \((x1,y1)\) to \((x2,y2)\) is( (x1 + x2) / 2, (y1 + y2) / 2 )