Yesterday I posted my Twitterable Mandelbrot, a ruby script that generates the Mandelbrot Set in 134 characters. A few of you took this as a challenge to shorten my code even further. I didn’t mind, and in fact was interested to see your results; I was sure that an extra character here or there could be shaved off.
What I didn’t expect at all was that somebody would shave fourteen characters off.
Reader brahbur on rubyflow came up with this:
80.times{|a|p (0..300).map{|b|x=y=i=0;(x,y,i=x*x-y*y+b/150.0-1.5,2*x*y+a/40.0-1,i+1)until(x*x+y*y>4||i>98);i>98?0:1}*''}
Brahbur’s solution does look different; there are quote marks on each line and it outputs 1s and 0s instead of #s and .s, but the mandelbrot is still clearly visible (Edit: I reduced the size from 300×80 to 240×60 just to keep the outputs roughly the same size):
Click for larger version (1400×800)
I think this is just awesome. Once we’re playing with 0’s and 1’s, I can see another optimization: i>98?0:1
can be replaced with 99i
. This bring us down to 118:
60.times{|a|p (0..240).map{|b|x=y=i=0;(x,y,i=x*x-y*y+b/120.0-1.5,2*x*y+a/30.0-1,i+1)until(x*x+y*y>4||i>98);99i}*''}
I have to give most of the credit to brahbur, though–I just saw a tiny tweak, on top of the amazing rewrite they already did. So great. THANK YOU brahbur!
Now, the challenge continues: can you shorten this further? Brahbur was concerned about “cheating”, so let’s define the rules for clarity: Output should be 240×60 (extra quotes and padding are okay) and it should be visually recognizable as a Mandelbrot set. Other than that, go for it.