使用递归打印对称整数序列,先倒数再倒数 [英] using recursion to print symmetric integer sequences that count down and then up
问题描述
我刚刚开始通过阅读书籍并完成练习来自学 Java.书中的一个练习是要求我编写一种使用递归打印对称整数序列的方法.例如:
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.
推荐答案
我可能和你读的是同一本书,我突然想到了这个.我无法用一种方法做到这一点,但我想无论如何我都会发布代码以显示不同的方式.
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.
public static void writeSequence(int n) {
int num = (int)Math.round(n / 2.0);
String flag = "";
if (n % 2 == 0) {
flag = "even";
} else {
flag = "odd";
}
System.out.println(writeSequence(num, flag));
}
private static String writeSequence(int n, String flag) {
if (n < 1) {
throw new IllegalArgumentException("less than one");
} else if (n == 1 && flag.equals("odd")) {
return "1";
} else if (n == 1 && flag.equals("even")) {
return "1 1";
} else {
return n + " " + writeSequence(n - 1, flag) + " " + n;
}
}
这篇关于使用递归打印对称整数序列,先倒数再倒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!