Search code examples
javarecursionsequencefractals

Method to return a fractal sequence (1 12 123 1234 ...) as a string, but last sequence is printing twice. (Java)


The point of this program is to return a "fractal sequence" up until some number, n. That sounds fancy, but all it means is that if, say, n = 4, then it would return: 1 1 2 1 2 3 1 2 3 4. (It just counts up to 1, then 2, then 3, then 4, and returns each step as it gets there.) To make it easier to see: 1 12 123 1234.

  1. The method is called "foo", and the main method must print it. So, the main method calls it by going System.out.print(foo(4)).

  2. The foo method must return a string.

  3. Loops may appear in the foo method, but the point of the exercise is to solve the problem recursively, and so the bulk of the work is supposed to feature a recursion. Or else, this would be a lot easier with some for loops!

    public class test{
      public static void main(String args[]){
    
        System.out.print(foo(4));
    
      }
      public static String foo(int n){
    
        String s = "";
    
    
        if(n == 1){               //Base step of the recursion
          s = 1 + " ";
        }
        else{
          s = foo(n-1) + n + " "; //Recursive step of the recursion    
        }
        System.out.print(s);      
        return s;
    
      }
    }
    

Right now, what the program will print is 1 1 2 1 2 3 1 2 3 4 1 2 3 4.

The problem is that it is printing out an extra set of 1 2 3 4 at the end. I realize the reason why it's doing that is because System.out.print(s) prints out everything I need, but then the extra System.out.print(foo(4)) in the main method is printing out the extra 1 2 3 4 at the end.

This could easily be solved if in the main method, I just took out System.out.print, and just wrote foo(4);. But, like rule (1) says, the main method must have the print. I'm not allowed to edit anything outside the foo method.

I have tried a bunch of different things (for about 7 hours or so now), but I don't seem to be "getting it". Can someone shed light on where I am going wrong?

Thank you sincerely!


Solution

  • This should work:

    pulic class test {
        public static void main(String args[]) {
            System.out.print(foo(4));
        }
    
        public static String foo(int n) {
            String s = "";
    
            if(n == 0) {    //do nothing      
            }
            else {
                s = foo(n-1);
                System.out.print(s);
                s=s+n;
            }      
            return s;
        }
    }