рекурсивные уровни и подсчет циклов

У меня есть домашнее задание, которое я готов сдать, в задании мне пришлось использовать рекурсию для рисования вложенных кругов на 10 уровней в глубину, после нескольких часов ударов головой об это я наконец завершил его. Мой единственный вопрос: это изображение, которое я рисую, имеет 10 уровней глубины или на самом деле 11?

Этот вопрос возникает из-за того, что я специально указал, что рекурсия заканчивается, когда она пройдет 10 уровней, но я говорю методу рисовать исходные круги, после чего он вызывает себя. это заставляет меня думать, что он рисует первый уровень, затем опускается на 10, чтобы в общей сложности было 11 уровней. изображение, которое он создает, заходит так далеко, что я не могу сосчитать круги :/

любые разъяснения будут оценены, спасибо!

    // import statements
    import java.awt.*;
    import javax.swing.*;

    public class RecursiveCircles 
    {

public static void main(String[] args) 
{
    // create a new canvas
    RCanvas myCanvas = new RCanvas();

    // create JFrame
    JFrame myJframe = new JFrame();
    myJframe.setTitle("Recursive Circles");

    // set JFrame size, location and close operation
    myJframe.setSize(1500, 500);
    myJframe.setLocation(100, 100);
    myJframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // and canvas to JFrame and make it visble
    myJframe.getContentPane().add(myCanvas);
    myJframe.setVisible(true);

     } // end main          
   } // end class RecursiveCircles

    /*
     * this class will draw the main circle of the image and will have the recursive
     * method that draws the two outer circles down 10 levels
     */

    class RCanvas extends Canvas 
    {
   // defualt constructor 
   public RCanvas ()
   {}

   public void paint (Graphics graphics)
   { 
       // declare variables
       String title = "Recursive Circles";

       int n = 300; // diamerter of the circle
       int xOrigin = 600; // x location of start of circle (makes circle around the origin I wanted
       int yOrigin = 100; // y location of start of circle (makes circle around the origin i wanted
       int radius = n/2; // radius of circle (half the diamerter

       int level = 10;

       // make canvas background color black
       graphics.setColor(Color.black); // make the background color black
       graphics.fillRect(0, 0, 1500, 500); // rectangle that fills the JFrame

       // put title on canvas
       graphics.setColor(Color.BLUE);
       graphics.drawString(title, 725, 50);

       // draw main circle
       graphics.setColor(Color.WHITE);
       graphics.drawOval(xOrigin, yOrigin, n, n);   

      drawRCircles(graphics,xOrigin,yOrigin,radius,level); // call recrusrive method
       System.out.println(level);

   } // end paint

   /*
    * This is the recursive method that will draw the two circles on the outer sides of the
    * main circle. it will then call itself and repate the process till it is 10 levels deep
    */
   public void drawRCircles(Graphics graphics,int xOrigin,int yOrigin, int radius, int level)
   {

   int newRadius = (radius/2); // radius of smaller circle
   int newXOrigin = xOrigin - (newRadius); // xOrigin of circle on left of the main circle
   int newYOrigin = yOrigin + (newRadius); // yOrigin of circle on the right of the main circle
   int newXOrigin2 = xOrigin + (newRadius*3); // xOrigin of circle on the right of the main circle
   int newYOrigin2 = yOrigin + (newRadius); // yOrigin of circle on the right of the main circle
       if (level > 0) // counts down from 10 to make the recursive image 10 levels deep
       { 
           graphics.drawOval(newXOrigin, newYOrigin, newRadius*2, newRadius*2); // draw recursive circle on the left of main circle
           graphics.drawOval(newXOrigin2, newYOrigin2, newRadius*2, newRadius*2); // draw recursive circle on the right of main circle
           drawRCircles(graphics, newXOrigin, newYOrigin , newRadius, (level-1)); // make recursion of left circle
           drawRCircles(graphics, newXOrigin2, newYOrigin2,newRadius,(level-1)); // make recursion of right circle

       }// end if
   } // end drawRCircles
  }// end class

person Jeffrey Quinn    schedule 17.02.2014    source источник


Ответы (1)


Ваш код рисует 11 кругов, но ваш вызов drawRCircles отвечает только за 10 из них.

Точнее, эти линии рисуют 1 круг.

    // draw main circle
    graphics.setColor(Color.WHITE);
    graphics.drawOval(xOrigin, yOrigin, n, n);  

Этот круг рисуется независимо от того, есть ли у вас функция drawRCircles. (Попробуйте удалить его и запустить свой код, чтобы посмотреть, что произойдет.)

Затем ваш код вызывает функцию drawRCircles 11 раз, но рисует только 10 кругов с момента последнего вызова, а уровень = 0 не проходит тест if(level > 0).

изображение, которое он создает, заходит так далеко, что я не могу сосчитать круги :/

Небольшой совет: поскольку вы хотите знать, будет ли при максимальном уровне N отображаться круги уровня N или N+1, вы также можете просто попробовать изменить свою переменную level на что-то более управляемое (например, 2) и проверить ее визуально.

Возвращаясь к вашему коду выше и игнорируя часть draw main circle (поскольку она не зависит от вашего рекурсивного рисования круга), у вас есть

    drawRCircles(graphics,xOrigin,yOrigin,radius,level); // call recursive method
    System.out.println(level);

и в вашей функции public void drawRCircles(…),

    drawRCircles(…,level-1);

Давайте проверим это с level = 2 вместо 10:

    drawRCircles(…, 2) 
        --> Check if 1 > 0.  
            --> Yes, 1 > 0 so drawRCircles(…, 1) 
                -->  Check if 0 > 0.
                    --> No, 0 = 0, so stop.

Количество уровней = 2 = количество нарисованных рекурсивных кругов.

person adilapapaya    schedule 17.02.2014
comment
Спасибо за информацию! оба опубликованных решения работают, но я собираюсь отметить ваш ответ как правильный, потому что вы также немного углубились в него и дали несколько советов, спасибо: D - person Jeffrey Quinn; 18.02.2014