public
Created

a couple of simple recursion examples

  • Download Gist
recursion.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 
 
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.