DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Patchwork Quilt Pattern In Ruby (from Knuth TAoCP 4 - 7.1.3)

02.27.2008
| 5055 views |
  • submit to reddit
        In Donald Knuth's TAoCP Pre-Fascicle 1a: Bitwise Tricks and Techniques, he shows a patchwork quilt defined by f(x, y) = ((x ^ y) & ((y - 350) >> 3)) ** 2, designed by D. Sleator in 1976. I wanted to recreate this quilt myself using Ruby. The following program generates a PNG file of the "quilt."

require 'rubygems'
require 'png'

def f(x, y)
  ( (x ^ y) & ((y - 350) >> 3) ) ** 2
end

canvas = PNG::Canvas.new(500, 500)

0.upto(499) do |y|
  0.upto(499) do |x|
    canvas[x, 499 - y] = ((f(x, y) >> 12) & 1) == 1 ? PNG::Color::Black : PNG::Color::White
  end
end

png = PNG.new(canvas)
png.save 'pattern.png'