It took me a fair bit of refactoring after I got the last test passing (generate 10 ) to get it this tight, but I like it.
def generate(n)
return [] if n == 1
factor = (2..n).find {|x| n % x == 0}
[factor] + generate(n / factor)
end
« svn replacement for git stash | Main | My New MVC Metaphor: The Command Line »
TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e54fb013da88340128759f141d970c
Listed below are links to weblogs that reference Kata:Ruby:Prime Factors:
» Kata:Ruby:Tail Recursive Prime Factors from Radyology
At the request of a former employer here's a tail recursive version of the prime factors kata in Ruby. def generate(n, factors=[]) return factors if n == 1 new_factor = (2..n).find {|f| n % f == 0} generate(n / new_factor,... [Read More]
You can follow this conversation by subscribing to the comment feed for this post.
This is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
Nice. Stuff like this makes me continue believe in programming.
Posted by: Fredrik Rubensson | November 27, 2009 at 08:48 AM
Can you make this tail recursive
Posted by: unclebob | December 05, 2009 at 09:48 AM
Sure can:
http://www.benrady.com/2009/12/katarubytail-recursive-prime-factors.html
Posted by: Ben Rady | December 05, 2009 at 02:50 PM