I've seen posts about this same problem, but I need to create the same triangle, only reflected. For example, if my recursive method rightTriangle
calls rightTriangle(4)
, the output should look something this:
Here is the working code that makes the right triangle of asterisks, but is reflected:
public static String rightTriangle(int n){
if( n <= 0 ){
return " ";
}
String line = rightTriangle(n - 1);
line = line "*";
System.out.println(line);
return line;
}
The output for rightTriangle(4)
is correct, with the exception that the triangle of asterisks prints out vertically reflected as opposed to the image above.
Any help would be greatly appreciated.
CodePudding user response:
A prefix of spaces might be needed to be passed as an argument to the recursive method:
public static void rightTriangle(int n) {
rightTriangle(n, "");
}
public static String rightTriangle(int n, String prefix) {
if( n <= 0 ) {
return "";
}
String line = rightTriangle(n - 1, prefix " ") "*";
System.out.println(prefix line);
return line; // only asterisks
}
Output for rightTriangle(4)
:
*
**
***
****
Update
A "single-method" version may look like this:
static int max = Integer.MIN_VALUE;
public static String rightTriangle(int n) {
if( n <= 0 ) {
return "";
}
max = Math.max(max, n);
String line = rightTriangle(n - 1) "*";
System.out.println(" ".repeat(max -(n - 1)) line);
return line;
}
Output for rightTriangle(5)
*
**
***
****
*****
CodePudding user response:
An alternative approach:
public static void main(String[] args) {
rightTriangle(4, 1, 1);
}
public static void rightTriangle(int totalLines, int currentLine, int n) {
if (currentLine <= totalLines) {
if (n <= (totalLines - currentLine)) {
System.out.print(" ");
}
else {
System.out.print("*");
}
if (n < totalLines) {
rightTriangle(totalLines, currentLine, n 1);
}
else {
System.out.println();
rightTriangle(totalLines, currentLine 1, 1);
}
}
}
Calling it with:
rightTriangle(10, 1, 1);
Produces:
*
**
***
****
*****
******
*******
********
*********
**********