Yash Jain
Yash Jain

Reputation: 31

How to print a given diamond pattern in Java?

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

Basically I just need the idea to put the spaces correctly. My code so far.

public class Pyramid3 {

    public static void main(String[] args) {

        int i, j;
        int noOfCol = 11;

        for (i = 1; i <= 11; i++) {

            for (j = 1; j <= noOfCol; j++) {
                System.out.print("*");
            }

            System.out.println();

            if (i == 1) {
                noOfCol--;
            } else if (i > 1 && i < 6) {
                noOfCol = noOfCol - 2;
            } else if (i > 6) {
                noOfCol = noOfCol + 2;
            }
        }
    }
}

Upvotes: 2

Views: 2623

Answers (6)

user16275053
user16275053

Reputation:

public static void main(String[] args) {
    int n = 7;
    for (int i = -n; i <= n; i++) {
        for (int j = -n; j <= n; j++)
            if (Math.abs(i) + Math.abs(j) >= n
                    // in chessboard order
                    && (i + j) % 2 != 0
                    // vertical borders
                    || Math.abs(j) == n)
                System.out.print("*");
            else
                System.out.print(" ");
        System.out.println();
    }
}

Output:

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

See also: Empty diamond shape with numbers

Upvotes: 0

Boris
Boris

Reputation: 805

Here's my solution to the exact diamond pattern you wanted.

I have a method, which makes printing easier for me.

private static void put(char c, int n, boolean NL) {
    for (int a = 0; a < n; a++) System.out.print(c);
    if (NL) System.out.println();
}

Basically, you tell it: which character to print, how many times, and whether it should add a new line after it finished printing.

Then comes the actual solution:

put('*', 11, true);
int count = 0;
for (int a = 5; a >= 1; a--) {
    put('*', (int) Math.ceil(a), false);
    put(' ', count++ * 2 + 1, false);
    put('*', (int) Math.ceil(a), true);
}
count = 4;
for (int a = 2; a < 6; a++) {
    put('*', (int) Math.ceil(a), false);
    put(' ', count-- * 2 - 1, false);
    put('*', (int) Math.ceil(a), true);
}
put('*', 11, true);

To be honest, there was a bit of brute-force logic, but the overall idea is simple. I keep track of spacing, via the counter variable and print the diamond's top and bottom separately.

Sorry for the lack of documentation as I didn't have much time when solving this. Hope it helps!

And for the lack of testing, here's the output.

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

Upvotes: 0

abd3lraouf
abd3lraouf

Reputation: 1658

This is the code, sorry for bad documentation, hope it helps.

PS: to solve any problem like this, just use a white paper and a pencil then make grids of columns and the index 'i' then figure a relation, then you can use it as loop condition.

public class Test {
    public static void main(String[] args) {
        int n = 10;

        // Top
        for (int i = n; i > 0; i--) {
            // Stars
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            // Spaces
            for (int j = i; j < n; j++) {
                System.out.print(" ");
            }
            // Stars
            for (int j = i; j < n; j++) {
                System.out.print(" ");
            }
            // Stars
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        // Bottom
        for (int i = 2; i < n + 1/* Note the shift here */; i++) {
            // Stars
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            // Spaces
            for (int j = i; j < n; j++) {
                System.out.print(" ");
            }
            // Spaces
            for (int j = i; j < n; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Hope it helps :)

Upvotes: 2

user14940971
user14940971

Reputation:

You can print an empty rhombus inscribed in a square using two nested streams over rows and columns from -n to n. The rhombus shape is obtained when n > iAbs + jAbs:

int n = 5;
String[] arr = IntStream
        .rangeClosed(-n, n)
        .map(Math::abs)
        .mapToObj(i -> IntStream
                .rangeClosed(-n, n)
                .map(Math::abs)
                // an empty rhombus inscribed in a square
                .mapToObj(j -> i + j < n ? " " : "*")
                .collect(Collectors.joining(" ")))
        .toArray(String[]::new);
Arrays.stream(arr).forEach(System.out::println);

Output:

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

See also:
Drawing numeric diamond
Empty diamond shape with numbers

Upvotes: 0

user3001
user3001

Reputation: 3487

I prefer answers which are short and concise. Mine exploits the horizontal and vertical symmetry axes of the diamond: The idea is to compute 1/4th of the diamond and then mirror it first around the vertical, then around the horizontal axis(_ is a space)

******
*****_
****__  
***___
**____
*_____

First, a short utitity function to repeat a character n times:

String repeat(String s, int times) {
  return times == 0 ? "" : new String(new char[times]).replace("\0", s);
}

Here is the code (using Java 8 lambdas for printing the result and this answer for reversing the string)

 // height and width of the diamond
int size = 11;
// Mhh diamonds
List<String> l = new ArrayList<>();
// len includes the axis, too
for (int i=0, len = size/2 + 1;i<len;i++) {
  String s = repeat("*", len - i) + repeat(" ", i);
  //Mirror, omitting the axis itself and append
  s += (new StringBuilder(s)).reverse().substring(1);
  l.add(s);
}
// Print the upper part
l.forEach(System.out::println);
// mirror around the horizontal axis
Collections.reverse(l);
// Omit the horizontan axis and print the rest
l.subList(1,l.size()).forEach(System.out::println);

That is 8-9 lines of code for a diamond of arbitrary size, plus 3 for the repeat method.

Result:

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

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

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:

**
**

***
* *
***

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

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

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

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

Upvotes: 2

Related Questions