Skip to content

Instantly share code, notes, and snippets.

@mather
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save mather/dbdac8391d21548e4993 to your computer and use it in GitHub Desktop.

Select an option

Save mather/dbdac8391d21548e4993 to your computer and use it in GitHub Desktop.
http://justindomke.wordpress.com/2008/11/29/mandelbrot-in-scala/ のマンデルブロ集合を描画するプログラムのリファクタ
import java.io._
import java.lang.Math
import scala.annotation.tailrec
/**
* ref: http://justindomke.wordpress.com/2008/11/29/mandelbrot-in-scala/
*/
object mandelbrot {
// tiny complex number class including syntactic sugar for basic operations
case class Complex(a: Double, b: Double){
// represents the complex number a + b*i
def +(that: Complex) = that match { case Complex(x,y) => Complex(a+x,b+y) }
def *(that: Complex) = that match { case Complex(x,y) => Complex(a*x-b*y,a*y+x*b) }
def abs = Math.sqrt(this.a*this.a + this.b*this.b)
}
def run(n: Int, level: Int) : Seq[Byte] = {
@tailrec
def divergenceSpeed(z: Complex, c: Complex, level: Int)(isDiverging: Complex => Boolean): Int = level match {
case 0 => 0
case l if isDiverging(z) => l
case l => divergenceSpeed(z * z + c, c , l-1)(isDiverging)
}
def px2axis(x: Int, y: Int, max: Int) = Complex(-2.0 + x*3.0/max, -1.5 + y*3.0/max)
for {
y0 <- 0 until n
x0 <- 0 until n
} yield {
val z = Complex(0,0)
val c = px2axis(x0,y0,n)
divergenceSpeed(z,c,level){ (_:Complex).abs > 2 } match {
case 0 => 0.toByte
case _ => 255.toByte
}
}
}
def main(args: Array[String]) {
val level = args(0).toInt
val pixels = args(1).toInt
val result = run(pixels, level)
val out = new FileOutputStream("scalaimage.pgm")
out.write(("P5\n"+pixels+" "+pixels+"\n255\n").getBytes())
out.write(result.to[Array])
out.close
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment