Patchwork Quilt Pattern In Ruby (from Knuth TAoCP 4 - 7.1.3)
Join the DZone community and get the full member experience.Join For Free
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'
Opinions expressed by DZone contributors are their own.