This code draws a tree, but it's not in the functional style.
tree[set_, m_] :=
Module[{θ, mz, my, temp, k, i, p1, p2, a, b, c, d, e, f},
θ = Pi/6;
mz = {{Cos[θ], -Sin[θ]}, {Sin[θ], Cos[θ]}};
my = {{Cos[-θ], -Sin[-θ]}, {Sin[-θ], Cos[-θ]}};
temp = set;
p1 = {};(*store branch*)
p2 = {};(*store leaf*)
For[k = 1, k <= m, k++, p2 = {};
For[i = 1, i <= Length[temp], i++, a = temp[[i, 2]];
b = temp[[i, 1]];
c = 1/3*a + 2/3*b;
d = c + mz.(a - b)*(1/3);
e = c + my.(a - b)*(1/3);
AppendTo[p1, {Brown, Thickness[0.035/k], Line[{b, c}]}];
AppendTo[p2, {c, a}];
AppendTo[p2, {c, d}];
AppendTo[p2, {c, e}];
];
temp = p2;
];
Show[Graphics[{p1, {RGBColor[0.1, 0.42, 0.17], Line[p2]}},
Axes -> 1, PlotRange -> {{-0.2, 0.2}, {-0.2, 1.}}]]];
tree[{{{0., 0.}, {0., 1.}}}, 7]
A friend of mine tried rewrite it with Nest
, but it worked slower than the original code.
(leaf = Nest[Apply[Transpose[{Table[(2 #1 + #2)/3, {3}],
{RotationTransform[-5 Pi/6, (2 #1 + #2)/3][#1],
RotationTransform[
5 Pi/6, (2 #1 + #2)/3][#1], #2}}] &, #, {-3}] &,
{{{0, 0.}, {0, 1}}}, 7];
Graphics[Map[{RGBColor[0.1, 0.42, 0.17], Line[#]} &, leaf, {-3}]]) // AbsoluteTiming
I think Nest
is slower than loops. How do I rewrite it to make it faster?
If possible, use Fold
, Nest
or similar functional constructs.