Created
November 14, 2012 12:37
-
-
Save vderyagin/4071857 to your computer and use it in GitHub Desktop.
cached fibonacci sequence generator in ruby
This file contains 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
#! /usr/bin/env ruby | |
require 'forwardable' | |
require 'minitest/autorun' | |
class Fibonacci | |
extend Forwardable | |
def_delegator :generator, :take | |
def initialize | |
@cache = [1, 1] | |
end | |
def [](num) | |
take(num + 1) unless @cache[num] | |
@cache[num] | |
end | |
def generator | |
Enumerator.new do |yielder| | |
current_idx = 0 | |
loop do | |
unless @cache[current_idx] | |
@cache << @cache[-1] + @cache[-2] | |
end | |
yielder << @cache[current_idx] | |
current_idx += 1 | |
end | |
end | |
end | |
private :generator | |
end | |
if __FILE__ == $PROGRAM_NAME | |
describe 'fibonacci sequence generator' do | |
before do | |
@fib = Fibonacci.new | |
end | |
it 'returns first item right' do | |
@fib[0].must_equal 1 | |
end | |
it 'returns second item right' do | |
@fib[1].must_equal 1 | |
end | |
it 'returns third item right' do | |
@fib[2].must_equal 2 | |
end | |
it 'returns fourth item right' do | |
@fib[3].must_equal 3 | |
end | |
it 'returns list right' do | |
@fib.take(10).must_equal [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] | |
end | |
end | |
end | |
# >> Run options: --seed 14468 | |
# >> | |
# >> # Running tests: | |
# >> | |
# >> ..... | |
# >> | |
# >> Finished tests in 0.000463s, 10804.3399 tests/s, 10804.3399 assertions/s. | |
# >> | |
# >> 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment