2

I got the exercise to write a function twice, once recursive, once iterative, which will produce the following output:

private static void printSequence(int n)

printSequence(3);

1
12
123
12
1

My iterative solution is the following:

for (int i = 1; i < 2 * n; i++) {
    for (int j = 1; j <= (i > n ? 2 * n - i : i); j++) {
        System.out.print(j);
    }
    System.out.println();
}

The iterative way is really simple, but I have no idea how to approach this as a recursive call.

Any tips on how to solve this problem?

EDIT: the method signature is fixed due to unit tests

2
  • You can create two recursive methods, one for printing numbers in one line, second to recursively print first and last rows (depending on input). Commented Nov 11, 2014 at 20:07
  • Hint: You want to print the first line, call a subroutine to fill in the middle, then print the last line. The subroutine then becomes exactly the same as the main method. Commented Nov 11, 2014 at 20:09

2 Answers 2

4

Your code should look like this

public static void main(String[] args) {
    recusiveFunction(1,10); // First parameter is the iteration number and 2 is total times.
}

private static void recusiveFunction(int iteration ,int total) {
    String str="";
    for(int i=1;i<=iteration;i++){ // this loops creates what it needs to print 1 or 12 or 123
        str+=i;
    }
    if(iteration<total/2){
        System.out.println(str);
        recusiveFunction(++iteration,total);
    }
    System.out.println(str);
}

Output:

1
12
123
1234
12345
1234
123
12
1

How this works is the we store the string in a variable that we want to print but we keep calling the function and increment the string is the iteration are less than half. then once it reaches half it start returning the stack trace so it gives us the return output in decreasing order.


Edit :

As said by pshemo modified the code a little bit to have absolutely no loops:

public static void main(String[] args) {
    recusiveFunction(1,10,"");
}

private static void recusiveFunction(int iteration ,int total, String str) {
    str+=iteration;
    if(iteration<total/2){
        System.out.println(str);
        recusiveFunction(++iteration,total,str);
    }
    System.out.println(str);
}

Output:

1
12
123
1234
12345
1234
123
12
1

Alternative way:

public class Main {
    private  static int iteration=1;
    private  static String str ="";

    public static void main(String[] args) {
        printSequence(10);
    }

    private static void printSequence(int total) {
        if(iteration<=total){
            str+=iteration;
            System.out.println(str);
            iteration++;
            printSequence(total);
        }
        if(2*total - iteration >0) {
            str = str.substring(0, 2 * total - iteration);
            iteration++;
            System.out.println(str);
        }
    }
}

Output:

1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
123456789
12345678
1234567
123456
12345
1234
123
12
1
Sign up to request clarification or add additional context in comments.

14 Comments

You are using loops. I would say that purpose of this exercise is to learn to rewrite loops as recursive methods.
@Pshemo the loop is only for constructing the string the is to be displayed.
So it should be fairly easy to rewrite it as recursive method :)
The method signature is fixed, it gets tested with some kind of unit test framework so i can't change it up... private static void printSequence(int n)
Anyway I would rather not to include it in your answer to avoid posting ready solutions. It is better if it will be hidden as comment to let others actually spend some time by themselves to improve or even rewrite your answer (I think it would be good exercise).
|
1

Hint: Your main recursive method can look like

void recursiveMethod(int iter, int max){
    if iteration<max
        print 1..iter
        recursiveMethod(iter+1, max)
        print 1..iter
    else
        print 1..iter
}

You can write additional recursive method which will handle printing numbers in range 1..n

        print 1..iter
        recursiveMethod(iter+1, max)
        print 1..iter

should handle printing

1
..
1

but will also invoke recursiveMethod(iter+1, max) which will fill .. part with

12
..
12

and so on, until case where iteration==max where we need to print only

123..max

3 Comments

this would be the way I would have solved it, but i can't add a parameter to the method signature due to unit tests which check my code
@chamm Like I said in my previous comment, you can simply invoke this recursive method inside method with fixed signature. Just set iter to 1 at start and let max be n.
In other words use private static void printSequence(int n){ recursiveMethod(1,n); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.