Tiny Recursions II

Came up with a short, recursive algorithm to calculate the perimeter of Koch snowflakes (Note that I wrote the code before looking it up on Wikipedia).

// file: "koch.scala"
def koch(length: Double, it: Int): Double = {
  def kochRec(currLength: Double, currIt: Int): Double = {
    if (currIt == 0) currLength
    else 4 * kochRec(currLength / 3, currIt - 1)
  }
  3 * kochRec(length, it)
}

The idea is this: Looking at only one side of the triangle, every iteration gives another four sides at 1/3 of it’s previous length. Multiplying by three at the end gives the correct perimeter after it iterations.


© 2024 Florian Klampfer

Powered by Hydejack v9.2.0