Never been to DZone Snippets before?

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

About this user

Peter Cooperx http://www.petercooper.co.uk/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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."

   1  
   2  require 'rubygems'
   3  require 'png'
   4  
   5  def f(x, y)
   6    ( (x ^ y) & ((y - 350) >> 3) ) ** 2
   7  end
   8  
   9  canvas = PNG::Canvas.new(500, 500)
  10  
  11  0.upto(499) do |y|
  12    0.upto(499) do |x|
  13      canvas[x, 499 - y] = ((f(x, y) >> 12) & 1) == 1 ? PNG::Color::Black : PNG::Color::White
  14    end
  15  end
  16  
  17  png = PNG.new(canvas)
  18  png.save 'pattern.png'
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS