go to previous page   go to home page   go to next page highlighting

Answer:

What is the easy problem that can be solved in one step?

Draw one rectangle.

What is the big problem that must be divided into smaller problems?

Draw all the rectangles:
  1. Draw one rectangle
  2. Draw the rectangles inside of it

Recursive Rectangles

Nine nested rectangles, centered in the window

This is similar to the cross-the-parking-lot problem:

Cross the parking lot:
  1. Take one step
  2. Cross the remaining distance by taking the remaining steps

Here is the program, again, but now written in recursive style:

import javafx.application.*;  
import javafx.stage.*;        
import javafx.scene.*;  
import javafx.scene.shape.*; 
import javafx.scene.paint.*;  

import java.util.Random;

public class DrawNestedRectangles extends Application
{ 
  double sceneWidth=400, sceneHeight= 300;  
  double centerX=sceneWidth/2, centerY=sceneHeight/2;

  private void fillGroup( Group gr, double scale )
  {
    double width=sceneWidth*scale, height=sceneHeight*scale;
    
    // Add one rectangle to the Group
    Rectangle rect = new Rectangle(  centerX-width/2, centerY-height/2, width, height );
    rect.setStrokeWidth( 2.0 );
    rect.setStroke( Color.RED );
    rect.setFill( Color.TRANSPARENT );
    gr.getChildren().add( rect );  

    // If there rectangles inside this one, add them to the Group
    if ( scale>=0.2 )
      fillGroup( gr, scale-0.1 );      
  }

  public void start(Stage stage) 
  { 
    Group  root = new Group( );   
    fillGroup( root, 0.9 );
    Scene scene = new Scene(root, sceneWidth, sceneHeight, Color.GHOSTWHITE ); 
    stage.setTitle("Recursive Rectangles"); 
    stage.setScene(scene); 
    stage.show(); 
  }      

} 

fillGroup() works by adding one rectangle at the supplied scale.

Then, if more rectangles are needed inside the one it just added, it adds them by calling itself with a reduced scale.


QUESTION 9:

The program, as written, first adds the outer rectangle to the group, then adds the inner rectangles.

Is is possible to add the inner rectangle first, and then add the rectangles that contain it?

The program, as written, reduces the scale each time by subtracting 0.1.

Is is possible to reduce the scale each time by multiplying by 0.9?

go to previous page   go to home page   go to next page