Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to create alternating triangle pyramid?

Tags:

java

I am trying to create a triangle pyramid of alternating "*" and "o" characters, with the number of rows being based on user input. The expected output I am trying to achieve, if the user inputs "6" for the number of rows, is:

      *
     *o*
    *o*o*
   *o*o*o*
  *o*o*o*o*
 *o*o*o*o*o*

The code I have written to achieve this is:

String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
    for (int j = 0; j < rows-i; j++){
        System.out.print(star);
    }
    for (int k = 0; k <= i; k++){
        System.out.print(circle);
    }
    System.out.println();
}

However, the output from my code does not match the pyramid above. The output of my code, with a user input of "6", is:

******o
*****oo
****ooo
***oooo
**ooooo
*oooooo

After spending the last three hours scouring both this website and others, I have still come up lost on how to alternate the characters, how to have the correct number of characters in each row, and how to format the pyramid as the expected output is. I don't know if my code is completely wrong, or if I am only missing a part to make it work correctly, but any advice or references is greatly appreciated.

like image 258
ccbadger Avatar asked Dec 25 '22 01:12

ccbadger


1 Answers

You could approach it another, far simpler, way.

In pseudo code:

  • create a String of n spaces
  • add "*" to it
  • loop n times, each iteration of the loop:
    • print it
    • replace " *" with "*O*"

This recognises a simple way to create the first line, and a simple way to create the next line from the previous line. Each replacement will match only the last (leading) space and the first star, replacing the space with a star, the star with an O and adding a star.

Usually the best way to solve a hard problem is to look at it in a way that makes it a simple problem (or a collection of simple problems).


A couple of ways to create a String of n spaces:

  • A loop that adds ' ' each iteration
  • new String(new char[n]).replace('\0', ' ')

How to replace certain characters of a String with other characters:

str = str.replace(" *", "*O*");
like image 76
Bohemian Avatar answered Jan 05 '23 16:01

Bohemian