Platinum Partner

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

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'
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}