Skip to content

Instantly share code, notes, and snippets.

@9999years
Last active May 18, 2017 17:17
Show Gist options
  • Save 9999years/2e6a8b89f3c1f16931b4f4227905971e to your computer and use it in GitHub Desktop.
Save 9999years/2e6a8b89f3c1f16931b4f4227905971e to your computer and use it in GitHub Desktop.
# generates the nth iteration of the koch snowflake and outputs
# it for use in LaTeX / tikz
# sources the iteration count from the args or defaults to 0
# you could easily modify it to request a default with
# iterations = int(prompt("iterations? ") or something
import sys
# get the first numeric argument for our iteration count
iterations: int
for arg in sys.argv:
try:
iterations = int(arg)
break
except ValueError:
pass
try:
iterations = max(iterations, 0)
except NameError:
iterations = 0
print("""\\begin{tikzpicture}
\t\\draw (0, 0)""", end="")
angle: int = 0
move_length = 1 / 3 ** (iterations - 1)
def turn(rel_angle):
global angle
angle += rel_angle
# format: -- ++(angle:length)
def move(rel_angle=angle, length=move_length):
global angle
angle += rel_angle
print("\n\t-- ++(" + str(angle) + ":" + str(length) + ")", end="")
def once(depth):
if depth > 0:
# recurse
# f-f++f-f
once(depth - 1)
turn(60)
once(depth - 1)
turn(-120)
once(depth - 1)
turn(60)
once(depth - 1)
else:
# base case / 0 iterations
move()
# axiom: f++f++f
# f → f-f++f-f
for i in range(0, 3):
once(iterations)
turn(-120)
print("""\n\t-- cycle;
\\end{tikzpicture}""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment