I am just starting to learn java on my own by reading a book and completing the exercises. One of the exercises on the book is asking me to write a method that prints symmetric integer sequences using recursion. For example:
writeSequence(1); //prints 1
writeSequence(2); //prints 1 1
writeSequence(3); //prints 2 1 2
writeSequence(4); //prints 2 1 1 2
writeSequence(5); //prints 3 2 1 2 3
writeSequence(6); //prints 3 2 1 1 2 3
So far, my solution uses two method implementations and doesn't look very elegant:
public class Client {
public static void main(String[] args) {
writeSequence(1);
writeSequence(2);
writeSequence(3);
writeSequence(4);
writeSequence(5);
writeSequence(6);
}
public static void writeSequence(int num) {
writeSequence( (int) Math.round(num/2.0), "desc", true);
if (num % 2 == 0) {
writeSequence( (int) Math.round(num/2.0), "asc", true);
} else {
writeSequence( (int) Math.round(num/2.0), "asc", false);
}
}
public static void writeSequence(int num, String direction, Boolean show_one) {
if (num < 1) {
throw new IllegalArgumentException("less than 1");
} else if (num == 1) {
if (show_one) {
System.out.print(1 + " ");
}
} else {
if (direction.equals("desc")) {
System.out.print(num + " ");
writeSequence(num-1, direction, show_one);
} else {
writeSequence(num-1, direction, show_one);
System.out.print(num + " ");
}
}
}
}
My question is: how do I solve this problem using only ONE method that must take only ONE parameter? Right now, I am implementing two methods but I only want to implement one to solve the problem.
Here's a hint about how to write only one recursive method with one argument.
Print your number both before and after the recursive call in your recursive method.
I might be reading the same book as you were and I came upon this. I wasn't able to do it in one method, but I thought I'd post the code anyway to show a different way.
I know it was an old post, but I've just literally went through this problem on praticeit and here is my solution