25
$\begingroup$

Here is some Maple code for drawing an L-System:

  with(Fractals:-LSystem)
  cons := ["A" = "draw:1", "+" = "turn:-90", "B" = "turn:90"]
  state, rules := "A", ["A" = "AB+BA+B", "B" = "B+AAB"]
  newstate1 := Iterate(state, rules, 7)

  LSystemPlot(newstate1, cons)

L-system

How can I make the same graphic using Mathematica?

I tried the first few steps:

SubstitutionSystem[{"A" -> "AB+BA+B", "B" -> "B+AAB"}, "A", {3}]
{"AB+BA+BB+AAB+B+AABAB+BA+B+B+AAB"} 
$\endgroup$
26
$\begingroup$
str = First@
   SubstitutionSystem[{"A" -> "AB+BA+B", "B" -> "B+AAB"}, "A", {7}];

asc = <|"A" -> {1, 0}, "B" -> {0, Pi/2}, "+" -> {0, -Pi/2}|>;

Here {1,0} means go forward 1 step and turn 0 radians. The turtle graphics substitute in Mathematica is AnglePath.

Graphics[
 Line@AnglePath@Lookup[asc, Characters[str]]
]

Thanks to @Pillsy, a shorter and faster way is

StringCases[str, {"A" -> {1, 0}, "B" -> {0, Pi/2}, "+" -> {0, -Pi/2}}]

Mathematica graphics

$\endgroup$
  • $\begingroup$ Nice. Cool knowledge of recent functions. $\endgroup$ – Vitaliy Kaurov Apr 9 '17 at 14:01
  • 3
    $\begingroup$ Sweet. You can also generate the angle path steps in a single step using StringCases. $\endgroup$ – Pillsy Apr 9 '17 at 14:10
  • 2
    $\begingroup$ @Vitaliy Actually I did not know SubstitutionSystem. I am happy to have learned something new. $\endgroup$ – Szabolcs Apr 9 '17 at 14:13
  • $\begingroup$ @Pillsy Indeed. It's faster too. Somehow I always thought of StringCases as a strictly string related function, and it simply did not occur to me to use it this way. $\endgroup$ – Szabolcs Apr 9 '17 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.