I've been curious about this as I was learning recursion.
I'm aware of recursive print methods like
public static void countdown(int n) {
if (n == 0) {
System.out.println("Blastoff!");
return;
} else {
System.out.println(n);
countdown(n - 1);
}
}
And ones that create "pyramids" But what about a pattern that's not simplistic or easy to code? For example,
public static void pattern(int n){
code;
}
Output if pattern(2);
Output if pattern(3):
Output if pattern(4):
I've been at the drawing board for a decent amount of time trying to figure out how someone would code/approach this. I tried it with the modulo operator, but the issue with it is limitation due to n being any # greater than 0.
I have also tried having cases, but that does not work either due to n being some number.
CodePudding user response:
In Java, if you want to use recursion but the parameters in the method header don't really lend themselves to it, then it's standard to make a helper method whose parameters are more appropriate, and internally call that.
In python, or another language that supports default parameters, you'd just make k
's default value fill itself in from n
, and expect callers to not provide it.
I've implemented your case as a recursion (it has different paths for if it's increasing, decreasing, or in the middle - and in either direction, it iterates in a range of [2 .. 2n-2]
with n
as the midpoint). It's kind of clumsy and could certainly be optimized, but you can get the picture - this is an awkward case to handle with recursion, it would be more straightforward with a simple while
loop.
public static void pattern(int n) {
_pattern(n, n);
}
private static void _pattern(int n, int k) {
// calculate number of characters to print
int d = n - Math.abs(k - n);
// base case - do nothing
if (d < 2) {
return;
}
// recursive flow
// note that, for the initial run, _both_ if statements activate
if (k <= n) {
_pattern(n, k - 1);
System.out.println(" ");
}
System.out.println(" ".repeat(d));
if (k >= n) {
System.out.println(" ");
_pattern(n, k 1);
}
}