From: Matthias Reitinger Date: 2009-03-25T07:04:37+09:00 Subject: Re: Midpoint Displacement (#197) Di Mo wrote: > ## Midpoint Displacement (#197) My solution utilizes Builder to print a SVG representation to stdout. Note that the enum_for(:each_cons, 2) construct could be replaced by a simple each_cons(2) when running Ruby 1.8.7 or 1.9.x. #!/usr/bin/env ruby require 'rubygems' require 'builder' require 'enumerator' # Options max_offset = 0.5 roughness = 0.5 iterations = 12 width = height = 100 style = "fill: black; stroke: none" # Midpoint displacement heights = [0.0, 0.0] iterations.times do heights = heights.enum_for(:each_cons, 2).map do |left, right| mid = (left + right) / 2 mid += (rand * 2 - 1) * max_offset [left, mid] end.flatten << heights[-1] max_offset *= roughness end # SVG output builder = Builder::XmlMarkup.new(:target => STDOUT) builder.instruct! builder.svg(:version => "1.1", :width => width, :height => height) do |svg| xs = (0...heights.size).map {|x| x.to_f / (heights.size - 1) * width} ys = heights.map {|y| (1 - y) * height * 0.5} points = [0, height] + xs.zip(ys) + [width, height] svg.polyline(:style => style, :points => points.join(" ")) end -Matthias -- Posted via http://www.ruby-forum.com/.