Created
September 5, 2012 12:24
-
-
Save egoholic/3635841 to your computer and use it in GitHub Desktop.
Stupid fibonacci numbers generator =)
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
class Fibquence < Array | |
def initialize(quantity = 0) | |
case quantity | |
when 0 | |
# nothing | |
when 1 | |
add_first | |
else | |
self << 0 << 1 | |
(quantity - 2).times { self << next_num } | |
end | |
end | |
def gen_next(quantity = 1) | |
quantity.times { self << next_num } | |
end | |
private | |
def add_first | |
self << 0 | |
0 | |
end | |
def prev | |
if empty? | |
add_first | |
elsif size == 1 | |
0 | |
else | |
self[-2] | |
end | |
end | |
def next_num | |
if prev.zero? | |
1 | |
else | |
prev + last | |
end | |
end | |
end | |
f = Fibquence.new(10) #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | |
f.size #=> 10 | |
f.gen_next | |
f.size #=> 11 | |
f.gen_next(1000) | |
f.size #=> 1011 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment