kellegous.com

 

Article

Pascal's Triangle in Ruby

June 28th 2006 in the wee hours

My friend Brent posted a solution to the most recent ruby quiz today. When I saw it, I tried to put it out of my mind. But curiosity, coupled with the fact that I seldom get to write any ruby these days, finally proved too much. As an act of rebellion against the overwhelming curiosity, I committed to do it in the most hideously unreadable form imaginable, a single expression …

#!/usr/bin/env ruby

puts (0...ARGV.first.to_i).inject([[1]]) { |a,x|
    a.unshift a.first.inject([0,[]]) { |b,y|
        [y,b.last << (b.first + y)]
    }.last + [1]
}.inject([]) { |c,z|
    next [z[z.length/2].to_s.length*2,z.length,""] if c.empty?
    [c[0],c[1], z.map { |j|
            j.to_s.center(c[0])
        }.join('').center(c[0]*c[1])+"\n#{c.last}"]
}.last
                                1                                 
                             1     1                              
                          1     2     1                           
                       1     3     3     1                        
                    1     4     6     4     1                     
                 1     5     10    10    5     1                  
              1     6     15    20    15    6     1               
           1     7     21    35    35    21    7     1            
        1     8     28    56    70    56    28    8     1         
     1     9     36    84   126   126    84    36    9     1      

Check out more ruby quizzes with far less hideous solutions in the ruby quiz archive.

trackbacks / pings

Pings are currently disabled; they will be accepted very soon.

comments

#1
brent

by far one of the trickier solutions i’ve seen. nice.

Post a Comment: To leave a new comment, simply type your message below. Markup is also allowed as long as it conforms to XHTML Strict. A list of allowable tags is available in the Comment Guidelines. Obviously, if the words “XHTML Strict” mean nothing to you, you should stick with just typing your message below.

about kellegous.com

kellegous.com is the personal site of kelly norton, a designer and engineer living in Atlanta, Georgia. Kelly used to be a graduate student at the MIT Media Lab but graduated in the summer of 2006. Before that, he was the Senior VP of Technology Development for Connexxia, a small technology company in Atlanta. He now works as a Software Engineer for Google. (more…)

now reading



syndicated feeds


 physical language workshop attribution-sharealike license / / xhtml / css