Return the following image: By rewriting the following function recursively: pub
ID: 3815915 • Letter: R
Question
Return the following image:
By rewriting the following function recursively:
public static void draw (double centerX, double centerY, double radius) {
if (radius < .0005) return;
StdDraw.setPenColor (StdDraw.LIGHT_GRAY);
StdDraw.filledCircle (centerX, centerY, radius);
StdDraw.setPenColor (StdDraw.BLACK);
StdDraw.circle (centerX, centerY, radius);
double change = radius * 0.90;
StdDraw.setPenColor (StdDraw.LIGHT_GRAY);
StdDraw.filledCircle (centerX + change, centerY + change, radius / 2);
StdDraw.setPenColor (StdDraw.BLACK);
StdDraw.circle (centerX + change, centerY + change, radius / 2);
StdDraw.setPenColor (StdDraw.LIGHT_GRAY);
StdDraw.filledCircle (centerX - change, centerY + change, radius / 2);
StdDraw.setPenColor (StdDraw.BLACK);
StdDraw.circle (centerX - change, centerY + change, radius / 2);
}
Explanation / Answer
To implement this as a recursive function, we need to understand what are the underlying subproblems that we are doing, and the terminating condition. Here, for each circle that we draw we are drawinng two more circles above it, and then same is done with those two smaller circles. The terminating condition is the bound (radius<0.0005). So here we are with the one solution:
public static void draw(double centerX, double centerY, double radius){
if (radius < 0.0005) return; // terminating condition
//first we draw our big circle
StdDraw.setPenColor(StdDraw.LIGHT_GRAY)
StdDraw.filledCicle(centerX, centerY, radius);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.circle(centerX, centerY, radius);
double change = radius * 0.90; // here is the change we do in further calls
// draw the upper right cicle
draw(centerX+change, centerY+change, radius/2);
//draw the upper left circle
draw(centerX-change, centerY+change, radius/2);
}
This code will work till the radius of the circles becomes less than 0.0005. I can not provide the output image since I will be needing the rest of the code for that.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.