Create a double mirror triangle

I need help creating a mirror triangle as follows:

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

I can get each separately, but I cannot combine them.

 public static void main(String[] args){ for( int i = 1; i <= 5; i++ ){ for( int j = 0; j < i; j++ ){ System.out.print("*"); } System.out.println(); } for(int i = 0; i < 6; i++) { for(int j = 5; j > 0; j--) { if(i < j) System.out.print(" "); else System.out.print("*"); } System.out.println(); } } 
+5
source share
4 answers

You can do this using this code.

 public class Test { public void sizeOfTri(int triSize) { //Number of lines int line = 1; for(int i = 0; i < triSize; i++) { //Handles Each line int temp = triSize * 2; for(int j = 1; j < temp; j++) { //Handles Each space on the line if(j <= line && j == triSize || j >= temp - line && j == triSize) { //For the very last line because it needs an extra * System.out.print("**"); } else if(j <= line || j >= temp - line) { //For normal lines System.out.print("*"); } else if(j == triSize) { System.out.print(" "); //For the second to last line because it needs an extra space to make it look mirrored } else { //For normal lines System.out.print(" "); } } System.out.println(); line++; } } public static void main(String[] args) { new Test().sizeOfTri(4); } } 

I commented on the following if statements about which part does what. This will result in an output that will look lower on startup

 * * ** ** *** *** ******** 
+3
source

You need to track the position on both sides so that you can show * in the right place. Here is the solution:

 for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { if (j <= i || j > 10 - i) { System.out.print("*"); } else { System.out.print(" "); } } System.out.println(); } 
+4
source

Although all of the above implementations are really good. I thought about doing it differently and using 2-D arrays.

 package algorithms; public class DrawMirror { static void initialize(String[][] array){ for (int i=0; i<MAX_X; i++){ for (int j=0; j < MAX_Y; j++){ array[i][j] = " "; } } } static void draw(String[][] array, int x, int y){ for (int i=0; i < y; i++){ array[x][i] = "*"; array[x][MAX_Y-i-1] = "*"; } } final static int MAX_X = 4; final static int MAX_Y = 8; public static void main(String[] args) { String[][] array = new String[MAX_X][MAX_Y]; initialize(array); for (int i=0; i < MAX_X ; i++){ draw(array,i,i+1); } for( int i = 0; i < MAX_X; i++ ){ for( int j = 0; j < MAX_Y; j++ ){ System.out.print(array[i][j]); } System.out.println(); } } } 
+2
source

The following code is a variable height function.

 public static void printDoubleTriangle(int height) { for(int i = 0; i < height; i++) { for(int j = 0; j < 2*height; j++) { if(j <= i || (2*height - j - 1) <= i) { System.out.print("*"); } else { System.out.print(" "); } } System.out.println(); } } 
+1
source

Source: https://habr.com/ru/post/1244534/


All Articles