Skip to content

Instantly share code, notes, and snippets.

@jballanc
Created May 6, 2009 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jballanc/107422 to your computer and use it in GitHub Desktop.
Save jballanc/107422 to your computer and use it in GitHub Desktop.
def ack(m, n)
if m == 0
n + 1
elsif n == 0
ack(m - 1, 1)
else
ack(m - 1, ack(m, n - 1))
end
end
def ack_catch(m, n)
if m == 0
throw :bottom, n + 1
elsif n == 0
catch :bottom do
ack_catch(m - 1, 1)
end
else
catch :bottom do
ack_catch(m - 1, ack(m, n - 1))
end
end
end
Bottom = Class.new(Exception)
def ack_raise(m, n)
if m == 0
raise Bottom, n + 1
elsif n == 0
begin
ack_raise(m - 1, 1)
rescue Bottom => value
return value.message
end
else
begin
ack_raise(m - 1, ack(m, n - 1))
rescue Bottom => value
return value.message
end
end
end
require 'ack'
require 'ack_catch'
require 'ack_raise'
require 'benchmark'
puts "Value for 'm'?"
m = gets.chomp.to_i
puts "Value for 'n'?"
n = gets.chomp.to_i
Benchmark.bm(3) do |test|
test.report("Recursive:") { puts "ack(#{m}, #{n}) => #{ack(m, n)}" }
test.report("Catch:") { puts "ack_catch(#{m}, #{n}) => #{ack_catch(m, n)}" }
test.report("Raise:") { puts "ack_raise(#{m}, #{n}) => #{ack_raise(m, n)}" }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment