To solve questions about ASCII art, one can try to find patterns in the different rows. One can see that each line contains a number of asterisks (*
), a number of spaces (possibly zero) and a number of asterisks.
So we first write a helper function:
public static String generateRow (int n1, int n2, int n3) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n1; i++) {
sb.append('*');
}
for(int i = 0; i < n2; i++) {
sb.append(' ');
}
for(int i = 0; i < n3; i++) {
sb.append('*');
}
}
Now we only need to work out the number of asterisks and spaces. The first and last line contain only n asterisks, so we can write:
System.out.println(generateRow(n,0,0));
The second line contains one space in the middle in case the n is odd, and two in case n is even, so this look like:
int ns = 2-(n%2);
int na = (n-ns)/2;
System.out.println(generateRow(na,ns,na));
Since na is the size minus the number of spaces divided by 2.
Now at each line, the number of spaces increases with two, so the number of asterisks is reduced by one. The loop stops if there is only one asterisks left. So you can rewrite this as:
int ns = 2-(n%2);
int na = (n-ns)/2;
for(; na >= 1; na--, ns += 2) {
System.out.println(generateRow(na,ns,na));
}
Now the lower part is simply produced by the opposite process. First we need to undo the last na
and ns
increment decrement:
na += 2;
ns -= 4;
And then we loop until the number of spaces is less than one:
for(; ns > 1; na++, ns -= 2) {
System.out.println(generateRow(na,ns,na));
}
putting it all together this resuluts in:
public static void generateDiamond (int n) {
System.out.println(generateRow(n,0,0));
int ns = 2-(n%2);
int na = (n-ns)/2;
for(; na >= 1; na--, ns += 2) {
System.out.println(generateRow(na,ns,na));
}
na += 2;
ns -= 4;
for(; ns >= 1; na++, ns -= 2) {
System.out.println(generateRow(na,ns,na));
}
System.out.println(generateRow(n,0,0));
}
jdoodle demo.
For sizes 2
, 3
, 5
, 8
, 11
, and 33
, this generates:
**
**
***
* *
***
*****
** **
* *
** **
*****
********
*** ***
** **
* *
** **
*** ***
********
***********
***** *****
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
***** *****
***********
*********************************
**************** ****************
*************** ***************
************** **************
************* *************
************ ************
*********** ***********
********** **********
********* *********
******** ********
******* *******
****** ******
***** *****
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
******** ********
********* *********
********** **********
*********** ***********
************ ************
************* *************
************** **************
*************** ***************
**************** ****************
*********************************