From: James Edward Gray II Date: 2007-05-28T02:18:59+09:00 Subject: Fwd: Please Forward: Ruby Quiz Submission --Apple-Mail-1-115650673 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed Begin forwarded message: > From: Geoff Hulette > Date: May 25, 2007 6:19:24 PM CDT > To: submission@rubyquiz.com > Subject: Please Forward: Ruby Quiz Submission > > Hi, I am new to this group so I hope I am doing this right. I > wrote a short ruby program that can render a Mandelbrot set to a > "MandelImage" object, which can then be printed as an ascii image > to the console. You could imagine writing an RMagick routine to > render it to a GIF or something instead. This solution is more the > spirit than the letter for this week's quiz, since I don't process > any command line args (but you could reuse the classes), and > Mandelbrot sets, while fractal, don't really have integer > "levels". If you run "ruby mandelbrot.rb", it should print first > the classic Mandelbrot set, and then similar-looking (but rotated) > cardioid, from deeper in the set. > -geoff > > --Apple-Mail-1-115650673 Content-Transfer-Encoding: 7bit Content-Type: text/x-ruby-script; x-unix-mode=0644; x-mac-creator=54784D74; name=mandelbrot.rb Content-Disposition: attachment; filename=mandelbrot.rb require 'Complex' class MandelbrotImage def initialize(data, max_iterations) @data = data @max_iterations = max_iterations end def to_s s = "" @data.each do |row| row.each do |i| case i when 0..5 s << ' ' when @max_iterations s << '##' else s << '..' end end s << "\n" end s end end class Mandelbrot def initialize(img_width, img_height) @img_width = img_width @img_height = img_height end def render(center, width, max_iterations=1000) from, to = convert_coords(center, width) pixel_size_y = (to.image - from.image)/@img_height pixel_size_x = (to.real - from.real)/@img_width image_data = [] (from.image..to.image).step(pixel_size_y) do |yc| row = [] (from.real..to.real).step(pixel_size_x) do |xc| c = Complex.new(xc, yc) z = Complex.new(0.0, 0.0) iteration = 0 while z.abs < 2.0 and iteration < max_iterations z = z**2 + c iteration += 1 end row << iteration end image_data << row end MandelbrotImage.new(image_data, max_iterations) end private def convert_coords(center, width) aspect = @img_height.to_f / @img_width.to_f height = width * aspect from = Complex.new(center.real - width/2.0, center.image - height/2.0) to = Complex.new(center.real + width/2.0, center.image + height/2.0) return from, to end end mandel = Mandelbrot.new(30, 20) image = mandel.render(Complex.new(-0.7, 0.0), 3.0769) puts image image = mandel.render(Complex.new(-0.743643135, 0.131825963), 4.3884e-06, 2000) puts image --Apple-Mail-1-115650673 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; format=flowed --Apple-Mail-1-115650673--