Instantly share code, notes, and snippets.

# tamouse/recursion.rb Created Jun 6, 2013

a couple of simple recursion examples
 def fibonacci(n,l=0) raise "#{n} is not a non-negative Integer" unless (n.is_a?(Integer) && n >= 0) STDERR.puts "Debug: level #{l}:\tn=#{n}" if \$debug return n if n <= 1 (fibonacci(n-1,l+1)+fibonacci(n-2,l+1)).tap{|t| STDERR.puts "Debug: Current calculation: #{t}" if \$debug} end def factorial(n,l=0) raise "#{n} is not a positive Integer" unless (n.is_a?(Integer) && n > 0) STDERR.puts "Debug: level #{l}:\tn=#{n}" if \$debug return n if n == 1 (n * factorial(n-1)).tap{|t| STDERR.puts "Debug: Current calculation: #{t}" if \$debug} end \$debug = false puts "Fibonacci from 1 to 10: " puts (1..10).reduce([]){|m,o| m << fibonacci(o)}.inspect puts "Factorials from 1 to 10: " puts (1..10).reduce([]){|m,o| m << factorial(o)}.inspect \$debug = true puts "Fibonacci from 1 to 10: " puts (1..10).reduce([]){|m,o| m << fibonacci(o)}.inspect puts "Factorials from 1 to 10: " puts (1..10).reduce([]){|m,o| m << factorial(o)}.inspect \$debug = false