dragon curve with L system using recursion in java

2.7k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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);
}

Try it online!