Skip to content

Instantly share code, notes, and snippets.

@ftclausen
Last active September 2, 2016 06:52
Show Gist options
  • Save ftclausen/bae0ff331548fe9a8d87a7426a1de533 to your computer and use it in GitHub Desktop.
Save ftclausen/bae0ff331548fe9a8d87a7426a1de533 to your computer and use it in GitHub Desktop.
Attempt at generating an L-System based pythagoras-like tree
var maxIterations = 3;
var currentIteration = 0;
var pythagorasTree = function(string, subIteration) {
// Because processing JS does not seem to like default parameters
if (!subIteration) {
currentIteration += 1;
}
if (currentIteration > maxIterations) {
println("Reached max iterations");
return;
}
var currentChar = "";
var newString = "";
while(string.length > 0) {
currentChar = string[0];
switch(currentChar) {
case "1":
newString += "11";
string = string.substring(1);
break;
case "0":
newString += "1[0]0";
string = string.substring(1);
break;
case "[":
newString += "[";
string = string.substring(1);
var results = pythagorasTree(string, true);
string = results.remaining;
newString += results.transformedText;
break;
case "]":
newString += "]";
string = string.substring(1);
// Can't return that object creation in-place, have to assign to variable.
// Otherwise Processing JS complains about unexpected ";"
var returnVals = { remaining: string, transformedText: newString };
return returnVals;
}
}
println(newString);
return pythagorasTree(newString);
};
/*
axiom: 0
1st recursion: 1[0]0
2nd recursion: 11[1[0]0]1[0]0
3rd recursion: 1111[11[1[0]0]1[0]0]11[1[0]0]1[0]0
*/
pythagorasTree("0");
@ftclausen
Copy link
Author

ftclausen commented Aug 29, 2016

L-system challenges and stepping stones

Production Rules

  • How to encode the rules
    • Use a hash e.g. Pythagoras tree ['1' => '11'] and ['0' => '1[0]0']
  • How to substitute one symbol for another according to the rules
    • Look it up in the hash
  • How to push position
    • Recurse when '[' is encountered
  • How to pop position
    • Return when ']' is encountered

Graphics

  • How to draw a line
  • How to calculate the angle of a line in relation to another
  • Draw a line at an angle to previous line

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment