CodingIsHard
CodingIsHard

Reputation: 19

Mirroring triangles using recursion Java

I need help making a mirrored triangle in java like in the question: Creating a double mirrored triangle. However it needs to be done using recursion. I figured out how to make two versions of the triangle already:
*
**
and
**
*
But I cant figure out the other alignments. That part of the assignment is not graded, it is to help our understanding so we can figure out how to do the mirrored image.

public static String triangle(int size) {
    if (size == 0)
        return "";

    String dots = triangle(size - 1);
    dots = dots + ".";
    System.out.println(dots);

    return dots;
}

//right alignment- small to big
public static String triangle2(int size) {
    if (size == 0)
        return "";

    String dots = "";
    for (int i = 0; i < size; i++){
        dots = dots + ".";
    }


    System.out.println(dots);
    return dots + triangle2(size - 1);

}
public static String triangle3(int size) {
    if (size == 0)
        return "";    

    String spaces = "";
    for (int i=0; i < size-1; i++){
        spaces = spaces + " ";
    }


    String dots = "";
    dots = dots + ".";

    System.out.println(spaces + dots);
    return spaces + dots + triangle3(size-1);

}

Upvotes: 1

Views: 280

Answers (1)

Andreas
Andreas

Reputation: 159086

Here is one solution, using two different recursive methods:

public static void printMirrorTriangle(int size) {
    printRow(1, size);
}
private static void printRow(int row, int size) {
    System.out.println(repeat('*', row) + repeat(' ', (size - row) * 2) + repeat('*', row));
    if (row < size)
        printRow(row + 1, size);
}
private static String repeat(char c, int count) {
    return (count == 0 ? "" : c + repeat(c, count - 1));
}

Test

printMirrorTriangle(4);

Output

*      *
**    **
***  ***
********

Upvotes: 1

Related Questions