Thursday, July 17, 2008

Cool Ruby One-Liner - Sierpinski Gasket

First found here referencing a twitter-updated Ruby golf entry, a nice snippet which generates the Sierpinski Gasket (or triangle) I was completely intrigued in the console. Like Giles from the first link I figured I should understand the mathematics used in generating the image but just didn't.

I "improved" the code to my liking since I like parameters for investigative purposes...

ruby -le 's=32; s.times{|y|print" "*(s-y-1),(0..y).map{|x|~y&x>0?" .":" A"}}'
I figured that the reason this code worked was based on a nice mathematical description of the underlying points. The example which hinted at this is to me is the Cantor Set. It has the beautiful definition as the set of points in the closed interval [0,1] such that the trinary expansion at any point contains no 1's (only 0's and 2's). The punchline is the Sierpinski Gasket has a similar description (documented here) and that's why the code works.

Math Nerd Editor's Note: The proof that the cantor-set is uncountable is based on the trivial mapping of the trinary expansions containing only 0's and 2's to the binary expansions containing 0's and 1's which describe all of the reals in [0,1] which itself is uncountable. How cool is that?

No comments:

Powered By Blogger