Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.