Created
January 11, 2011 11:27
-
-
Save lantoli/774315 to your computer and use it in GitHub Desktop.
Fibonacci numbers using 4 different algorithms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec' | |
class Integer | |
def to_fib | |
return to_fib_formula unless self < 10 | |
to_fib_tail | |
end | |
def to_fib_recursive | |
return self if zero? or one? | |
(self-1).to_fib_recursive + (self-2).to_fib_recursive | |
end | |
def to_fib_tail | |
return self if zero? or one? | |
first,second = 0,1 | |
(self-1).times do | |
first,second = second, first + second | |
end | |
second | |
end | |
def to_fib_inject | |
return self if zero? or one? | |
fib = (self-1).times.inject( [0,1] ) do | group, n | | |
[ group[1], group[0] + group[1] ] | |
end | |
fib[1] | |
end | |
def to_fib_formula | |
( ( (GOLDEN_RATIO**self) - ((-GOLDEN_RATIO)**(-self)) ) / ROOT_FIVE ).to_i | |
end | |
def one? | |
self == 1 | |
end | |
ROOT_FIVE = Math.sqrt(5) | |
GOLDEN_RATIO = (1 + ROOT_FIVE) / 2 | |
end | |
describe "Fibonacci" do | |
context "testing basic Fibonacci numbers." do | |
it "Fibonacci number 0 is 0" do | |
0.to_fib.should == 0 | |
end | |
it "Fibonacci number 1 is 1" do | |
1.to_fib.should == 1 | |
end | |
it "Fibonacci number 2 is 1" do | |
2.to_fib.should == 1 | |
end | |
it "Fibonacci number 3 is 2" do | |
3.to_fib.should == 2 | |
end | |
it "Fibonacci number 10 is 55" do | |
10.to_fib.should == 55 | |
end | |
it "Fibonacci number 30 is 832040" do | |
30.to_fib.should == 832040 | |
end | |
it "Fibonacci number 38 is 39088169" do | |
38.to_fib.should == 39088169 | |
end | |
end | |
context "testing all the implementations." do | |
0.upto(30) do |i| | |
it "recursive impl for number #{i}" do | |
i.to_fib_recursive.should == i.to_fib | |
end | |
it "tail impl for number #{i}" do | |
i.to_fib_tail.should == i.to_fib | |
end | |
it "inject impl for number #{i}" do | |
i.to_fib_inject.should == i.to_fib | |
end | |
it "formula impl for number #{i}" do | |
i.to_fib_formula.should == i.to_fib | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment