Posts Tagged ‘mandelbrot’

Mandelbrot with Scala and Java

Wednesday, September 16th, 2009

I’m testing if Scala can be used to increase productivity here. Pretty nice language: as powerful as Ruby and JVM-compatible. To improve my skills, I decided to implement Mandelbrot on Scala, using Swing’s BufferedImage to show the image. Very simple, indeed. The code is:

import java.awt.image.BufferedImage
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel
object Mandelbrot extends Application {
  case class Complex(r : Double, i : Double) {
    def +(b : Complex) = Complex(r + b.r, i + b.i)
    def *(b : Complex) = Complex(r * b.r - i * b.i, r * b.i + i * b.r)
    def insideM = (r * r + i * i) < (2 * 2)
  }

  implicit def start = Complex(0, 0)

  def pc(z : Complex, c : Complex) : Complex = z * z + c

  def iter(qtd : Int, c : Complex)(implicit z : Complex) : Int = {
    if (qtd == 0) 0
    else if (!z.insideM) qtd
    else iter(qtd - 1, c)(pc(z, c))
  }

  val scale = 1.0
  def pixToComplex(x : Double, y : Double) =
    Complex(((x / 640.0) * 3.0 - 2.0) / scale,
        ((y / 480.0) * 2.0 - 1.0) / scale)

  def raster(f : (Int, Int, Int) => Unit) = {
    for (y <- 0 until 480; x <- 0 until 640) {
      f(x, y, iter(1024, pixToComplex(x, y)))
    }
  }

  def qtdToColor(c : Int) = List(c / 4, c / 4, c / 4).toArray

  val frame = new JFrame("Mandelbrot")
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

  val lbl = new JLabel
  frame.add(lbl)
  frame.setSize(640, 480)
  frame.setVisible(true)

  val img = new BufferedImage(640, 480, BufferedImage.TYPE_3BYTE_BGR)
  raster((x, y, c) => img.getRaster.setPixel(x, y, qtdToColor(c)))
  lbl.setIcon(new ImageIcon(img))
}

Since I’m new to Scala, I guess it’s not the best solution. Nevertheless, I have an “Yes-we-can” feeling, because this code have some Scala features, like higher-order functions and (possibly) tail recursion. And, of course, I felt productive implementing Mandelbrot’s recursive algorithm (I got a lot of errors misunderstanding the algorithm, BTW).