"Mandelbrot — escape-time iteration of z := z² + c starting at z₀ = 0.
 Returns the number of iterations before |z|² exceeds 4, capped at
 maxIter. Classic-corpus program for the Smalltalk-on-SX runtime."

Object subclass: #Mandelbrot
  instanceVariableNames: ''!

!Mandelbrot methodsFor: 'iteration'!
escapeAt: cx and: cy maxIter: maxIter
  | zx zy zx2 zy2 i |
  zx := 0. zy := 0.
  zx2 := 0. zy2 := 0.
  i := 0.
  [(zx2 + zy2 < 4) and: [i < maxIter]] whileTrue: [
    zy := (zx * zy * 2) + cy.
    zx := zx2 - zy2 + cx.
    zx2 := zx * zx.
    zy2 := zy * zy.
    i := i + 1].
  ^ i!

inside: cx and: cy maxIter: maxIter
  ^ (self escapeAt: cx and: cy maxIter: maxIter) >= maxIter! !

!Mandelbrot methodsFor: 'grid'!
countInsideRangeX: x0 to: x1 stepX: dx rangeY: y0 to: y1 stepY: dy maxIter: maxIter
  | x y count |
  count := 0.
  y := y0.
  [y <= y1] whileTrue: [
    x := x0.
    [x <= x1] whileTrue: [
      (self inside: x and: y maxIter: maxIter) ifTrue: [count := count + 1].
      x := x + dx].
    y := y + dy].
  ^ count! !
