Reputation: 197
I want to compute dragon curve till n = 10 in java with L system using recursion. For example,
Replace all F characters with F-H
Replace all H characters with F+H
dragon(0) = F-H (this is the input)
dragon(1) = F-H-F+H
dragon(2) = F-H-F+H-F-H+F+H
...
dragon(10) = ?
How can I accomplish the same in java using recursion? I'm only interested in knowing the recursive approach.
Upvotes: 0
Views: 2908
Reputation: 1949
In recursive approach such "replace" problem statements usually can be implemented as recursive calls.
So let's create two functions - F()
and H()
each of them will return "F"
or "H"
when desired curve depth is reached, or F(...) + "-" + H(...)
or F(...) + "+" + H(...)
if further expansion is needed.
private String F(int depth) {
if (depth == 0) {
return "F";
} else {
return F(depth - 1) + "-" + H(depth - 1);
}
}
private String H(int depth) {
if (depth == 0) {
return "H";
} else {
return F(depth - 1) + "+" + H(depth - 1);
}
}
public String dragon(int depth) {
return F(depth + 1);
}
Upvotes: 0