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).

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.


© 2017. All rights reserved.

Powered by Hydejack v7.0.0-beta.0