Java triangle of n height using recursion

前端 未结 2 1776
暖寄归人
暖寄归人 2021-01-28 01:39

Assume the availability of a method named makeLine that can be passed a non-negative integer n and a character c and return a String consisting of n identic

相关标签:
2条回答
  • 2021-01-28 02:01

    I won't give you the answer, but hopefully this gives you some hints. A recursive method is something that solves a problem by calling itself to solve a smaller version of the same problem. In your case, the problem is to print this (I've put b where blanks belong):

    OOOOO
    bOOO
    bbO
    

    You're printing the first line, then solving a smaller version of the same problem, which is to print a smaller triangle:

    bOOO
    bbO
    

    The problem is that this smaller version isn't quite the same; it has to have extra spaces before each line. How much extra space? Well, that's why the instructor said "use k to your advantage". How could you call the method recursively, and use k to tell it to display extra spaces?

    0 讨论(0)
  • 2021-01-28 02:07

    I have a problem of solving people's "homework". I'll explain how this works to help you learn.

    Here is how the code works.

    First, like you did, you must check if the value n is odd. If it is, increment the value like you have, to make it even.

    Now you need to build your 'triangle'. Do this by using recursion. For each row of the triangle, you need to print the spaces, then the 'O's, then end the line by printing the spaces.

    In your example the 'X's represent spaces, and the 'O' represent the triangle:

    OOOOO
    XOOOX
    XXOXX
    

    Furthermore, look at a bigger example:

    OOOOOOOOO
    XOOOOOOOX
    XXOOOOOXX
    XXXOOOXXX
    XXXXOXXXX
    

    As you can see, each time a new line is added, one extra space is added on each side. Therefore, you can use 'k' to your advantage to print the spaces. Added 1 to 'k' for each recursive execution, will take care of this. Now you simply have to edit your System.out.println() statement to add the makeLine so that you draw the spaces (or 'X's), as well as the 'O's.

    public void printTriangle(int n, int k){ 
        if(n <= 0)
            return;
        if(n % 2 == 0) 
            n++;
        System.out.println(makeLine(k, ' ') + makeLine(n, 'O') + makeLine(k, ' '));
        printTriangle(n-2, k+1); 
    }
    

    Hope this helps! Please feel free to ask questions if you have them.

    0 讨论(0)
提交回复
热议问题