Randy B.
Randy B.

Reputation: 59

Java recursion to output number pattern

Required output:

    5
   454
  34543
 2345432
123454321

How can I do this using recursion? I have the code idea which is:

public static void main(String[] args)
{
      System.out.println(func(5)); 
}
public static String func(int num)
{
     return num + "" +meth(num-1, num, num-1);
}

public static String meth(int start, int num, int end)
{

    if(start==1)
    {
        return "1";
    }
    System.out.println(start+num+end);

    return meth(start-1, num, end-1);
}

I am confused about what to return in the if statement and the System.out.println(), because the number 5 won't decrease/increase as it will stay for example, it will stay 5 vertically, how can I deal with this problem? my code is more of an illustration just to prove that I am doing it.

Upvotes: 0

Views: 1261

Answers (2)

programmer23
programmer23

Reputation: 543

I think that just passing the num by parameter and the previous String (which is the previous row):

private static String meth(int num,String previous) {

     String space="";
    for(int i=0; i<num; i++) space+=" ";
    //If number is negative, return empty String
    if(num<=0) return "";

    //if number is 1, we need to check if previous string is empty or not, because if is empty we need then umber only once, otherwise we need to add to the string
    else if(num==1){
        if(!previous.isEmpty()) return space+num+previous+num;
        else return space+num+"";
    }

    //Here is checked if previous is empty and we do the same as before with number one
    String currentRow=previous.isEmpty()? String.valueOf(num) : num+previous+num;

    //We return the current row (with the current number), and we add the next row (or tree level) passing the number-1 and the row we have
    return space+currentRow+"\n"+meth(num-1,currentRow);

}

Upvotes: 0

esin88
esin88

Reputation: 3199

Maybe this is what you're looking for:

public class Main {
    public static void main(String[] args) {
        startRecursion(5);
    }

    private static void startRecursion(int number) {
        String aligner = "";
        for (int i = 0; i < number - 1; i++) {
            aligner += " ";
        }
        recursion(String.valueOf(number), number, number, aligner);
    }

    private static void recursion(String value, int startNumber, int lastNumber, String aligner) {
        if (lastNumber < 1) {
            return;
        }

        if (lastNumber != startNumber) {
            value = lastNumber + value + lastNumber;
        }

        System.out.println(aligner + value);

        if (!aligner.isEmpty()) {
            aligner = aligner.substring(0, aligner.length() - 1);
        }

        recursion(value, startNumber, lastNumber - 1, aligner);
    }
}

Prints:

    5
   454
  34543
 2345432
123454321

Upvotes: 2

Related Questions