I have two implementation which I modified according to my need to create a triangle or a pyramid like this:
*
***
*****
*******
*********
First way:
int num = 5;
for(int i=0;i<num;i++) {
for(int j=0;j<num-i;j++) {
System.out.print(" ");
}
for(int k=0;k<=i;k++) {
System.out.print((k==0)?"*":"**");
}
System.out.println();
}
Second way:
int num = 5, spaces = num - 1, charData = 2 * num;
String str = String.join("", Collections.nCopies(spaces, " ")) + String.join("", Collections.nCopies(charData, "*"));
for (int i = 0; i < num; i++)
System.out.println(str.substring(i, num + 2*i));
The second way seems shorter than the first one which takes fewer lines of code and fewer loops. I would like to find out which one is shorter and more efficient. Is there any other way the code can become shorter and more efficient with fewer loops?