anlam456
anlam456

Reputation: 53

Triangle Word Pattern using Nested Loops in Java

For this assignment, after inputting any word, it will print it in a pattern shown below (in this case, the word is computer):

       C
      O O
     M   M
    P     P
   U       U
  T         T
 E           E
RETUPMOCOMPUTER

Currently, my code is this:

    String output = "";
        for (int a = word.length()-1; a >= 1; a--)
        {
            for (int b = 0; b < word.length(); b++)
            {
            out.print(" ");
            }
        out.println(word.charAt(word.length()-1-a));
        }

        for (int c = 0; c < word.length(); c++)
        {
            out.print(word.charAt(word.length()-1-c));  
        }
        out.print(word.substring(1));   
    return output + "\n";

The output for my code currently is:

        C
        O
        M
        P
        U
        T
        E
RETUPMOCOMPUTER

Any advice or tips is much appreciated, thank you in advance!

Upvotes: 4

Views: 6850

Answers (4)

user3437460
user3437460

Reputation: 17454

You asked for nested loops, but there are a few other ways including padding it with spaces. If you are allowed to do that, you only need a single loop:

public static void printTriangle(String str){       
    int len = str.length()-1, idx = 1;

    System.out.println(String.format("%"+(len+1)+"s", str.charAt(0)));
    for(int x=0; x<str.length()-2; x++){
        System.out.print(String.format("%"+(len--)+"s", str.charAt(idx)));
        System.out.println(String.format("%"+(idx*2)+"s", str.charAt(idx++)));
    }
    System.out.println(new StringBuilder(str.substring(1)).reverse().toString() + str);
}

Output:

       C
      O O
     M   M
    P     P
   U       U
  T         T
 E           E
RETUPMOCOMPUTER

Upvotes: 1

Pham Trung
Pham Trung

Reputation: 11294

The logic is simple, first try to create the last line, using reverse of StringBuilder. Then print each line from the first to the last line.

The last line case is simple.

From the first to the last line - 1, we only need to print those characters that has the distance equal 0, 1, 2 ... to the center of the last line.

    public void printTriangle(String input) {
        String tmp = input.substring(1);//Take the suffix
        StringBuilder builder = new StringBuilder(tmp);
        builder = builder.reverse().append(input);//Reverse, then append it
        String line = builder.toString();//This is the last line
        for(int i = 0; i < input.length(); i++){
            for(int j = 0; j < line.length(); j++){
                //Print the last line, or those that have distance equals i to the center of the last line
                if(i + 1 == input.length() || Math.abs(j - line.length()/2) == i){
                    System.out.print(line.charAt(j));
                }else{
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

Input

COMPUTER

Output

       C       
      O O      
     M   M     
    P     P    
   U       U   
  T         T  
 E           E 
RETUPMOCOMPUTER

Input

STACKOVERFLOW

Output

            S            
           T T           
          A   A          
         C     C         
        K       K        
       O         O       
      V           V      
     E             E     
    R               R    
   F                 F   
  L                   L  
 O                     O 
WOLFREVOKCATSTACKOVERFLOW

Upvotes: 2

Henrique Barcelos
Henrique Barcelos

Reputation: 7900

Suppose you have a string str of length n. You'll have a matrix of size n × 2n+1.

First, you need to define the center c of your triangle, which would be the position n

In your first line of the matrix, you draw only the first letter (str[0]) in the center and then go to the next line.

In the second line, you draw the second letter (str[1]) in the positions c-1 and c+1.

In the third line, you draw the third letter (str[2]) in the positions c-2 and c+2.

And so on.

The last line is the trickier. Starting from the center c, you have to draw the whole word str. From the center, you start writing your string forwards and backwards.


I've tried some implementation, it's really simple:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str = br.readLine();

int n = str.length();

char[][] matrix = new char[n][2*n+1];

char[] chrArr = str.toCharArray();

// initializes the matrix with blank spaces
for (int i = 0; i < n; i++) {
    for (int j = 0; j < 2*n+1; j++) {
        matrix[i][j] = ' ';
    }
}

// build the two sides of the triangle
for (int i = 0; i < n - 1; i++) {
    matrix[i][n-i] = chrArr[i];
    matrix[i][n+i] = chrArr[i];
}

// last line, build the base of the triangle
for (int i = 0; i < n; i++) {
    matrix[n-1][n-i] = chrArr[i];
    matrix[n-1][n+i] = chrArr[i];
}

// print
for (int i = 0; i < n; i++) {
    for (int j = 0; j < 2*n+1; j++) {
        System.out.print(matrix[i][j]);
    }
    System.out.print("\n");
}

Here is the sample code running in ideone. You can try it with any string size.

Upvotes: 0

Liron Ilayev
Liron Ilayev

Reputation: 386

Instead of doing a code that will magically work for every case, try using a code that addresses every case:

String someString = "COMPUTER";
    switch(someString.length()) {
    case 0: System.out.println();
            break;
    case 1: System.out.println(someString);
            break;
    default:
        int _spaces_before_after = someString.length()-1;
        int _spaces_middle = 0;
        for(int i=0; i<someString.length(); i++){
            if(i!=someString.length()-1){
                if(i==0){
                    for(int j=0; j<_spaces_before_after; j++)
                        System.out.print(" ");
                    System.out.print(someString.charAt(0));
                    for(int j=0; j<_spaces_before_after; j++)
                        System.out.print(" ");
                    System.out.println();
                    _spaces_middle = 1;

                }
                else {
                    for(int j=0; j<_spaces_before_after; j++)
                        System.out.print(" ");
                    System.out.print(someString.charAt(i));
                    for(int j=0; j<_spaces_middle; j++)
                        System.out.print(" ");
                    System.out.print(someString.charAt(i));
                    for(int j=0; j<_spaces_before_after; j++)
                        System.out.print(" ");
                    System.out.println();
                    _spaces_middle+=2;
                }
                _spaces_before_after-=1;
            }
            else {
                for(int j=someString.length()-1; j>=0; j--)
                    System.out.print(someString.charAt(j));
                for(int j=1; j<someString.length(); j++)
                    System.out.print(someString.charAt(j));
            }
        }
        break;
    }

Upvotes: 0

Related Questions