Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text Pyramid using recursion in Java

Tags:

java

recursion

I am trying to make a full triangle with any text input. Example if I have string that is "abcdefghij" I want the result to be

    aj
   abij
  abchij
 abcdghij
abcdefghij

if the string length is odd as in "abcdefghij" then the output would be

    a
   abi
  abchi
 abcdghi
abcdefghi

Here is what I have so far but my output for the words is upside down. My output is

    abcdefghij
   abcdghij
  abchij
 abij
aj

What I have done so far

public static void main(String[] args) {

        solve("abcdefghij");

    }

    public static void solve(String word) {

        solve(word, word.length()/2-1);

    }

    public static void solve(String word, int it) {

        // print starting spaces
        for(int i = 0; i < it; i++)
            System.out.print(" ");

        // print out string
        System.out.print(word+"\n");


        if(word.length() > 2) {

            int newlengthperside = (word.length() - 2)/2;
            solve( word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it-1);

        }
    }

I just need a suggestion on how to start from aj instead of the end. Thanks for any help. This is homework so just a hint is appreciated.

like image 501
Dilawer Hussain Avatar asked Oct 30 '22 14:10

Dilawer Hussain


1 Answers

You code should look like this :

 public void solve(String str) {
    for(int i=1;i<=str.length()/2;i++) {
        for(int j=str.length()/2-i; j>0 ;j--) {
            System.out.print(" ");
        }
        System.out.print(str.substring(0,i));
        System.out.print(str.substring(str.length()-i));
        System.out.println();
    }
}

Input :

"abcdefghij"

Output:

    aj
   abij
  abchij
 abcdghij
abcdefghij

This only covers the happy path but you show understand the logic.


EDIT :

For recursive approach :
public static void solve(String word) {
    solve(word, 0);
}

public static void solve(String word, int it) {

    // print starting spaces
    String spaces="";
    for(int i = 0; i < it; i++)
        spaces+=" ";


    if(word.length() > 2) {
        int newlengthperside = (word.length() - 2)/2;
        solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it + 1);
    }
    System.out.print(spaces+word+"\n");
}

I changed a few things:
1. counting number of spaces needed and putting them in a string which is used later on.

String spaces="";
for(int i = 0; i < it; i++)
  spaces+=" ";
  1. solve(word, 0); //-> 0 from length

  2. solve(word.substring(0, newlengthperside) + word.substring(word.length() - newlengthperside), it + 1); //-> adding 1 to the length

Input :

solve("abcdefghij");

Output :

    aj
   abij
  abchij
 abcdghij
abcdefghij
like image 95
StackFlowed Avatar answered Nov 15 '22 05:11

StackFlowed