Generating a pattern from user-defined rules
For the 5th iterate:
Nest[
Replace[#, {L -> Sequence[L, S], S -> Sequence[L]}, {1}] &,
{L},
5
]
{L, S, L, L, S, L, S, L, L, S, L, L, S}
And for the list of first 5 iterates:
NestList[
Replace[#, {L -> Sequence[L, S], S -> Sequence[L]}, {1}] &,
{L},
5
]
{{L}, {L, S}, {L, S, L}, {L, S, L, L, S}, {L, S, L, L, S, L, S, L}, {L, S, L, L, S, L, S, L, L, S, L, L, S}}
Edit:
SubstitutionSystem
operates on strings instead. It is a bit faster because it is specifically designed for Lindenmayer systems:
L = "L";
S = "S";
a = StringJoin /@ NestList[
Replace[#, {L -> Sequence[L, S], S -> Sequence[L]}, {1}] &,
{L},
20
]; // AbsoluteTiming // First
b = SubstitutionSystem[{"L" -> "LS", "S" -> "L"}, "L", 20]; // AbsoluteTiming // First
a == b
0.004506
0.001265
True
PS.: As Carl Woll pointed out, the following will return only the 20th iterate.
c = SubstitutionSystem[{"L" -> "LS", "S" -> "L"}, "L", {20}];
You may use ReplaceRepeated
with its MaxIterations
option.
ReplaceRepeated[{L}, {L -> Sequence[L, S], S -> Sequence[L]},
MaxIterations -> 5]
{L, S, L, L, S, L, S, L, L, S, L, L, S}
Hope this helps.
A recursive method:
ClearAll[f]
f[L] = Sequence[L, S];
f[S] = L;
f[a__, b_] := f[a, b] = Sequence[f @ a, f @ b]
List @ Nest[f, L, 7]
{L, S, L, L, S, L, S, L, L, S, L, L, S, L, S, L, L, S, L, S, L, L, S, L, L, S, L, S, L, L, S, L, L, S}