Last active
April 16, 2021 15:33
-
-
Save harsh183/2c3a83ec356a16d4cf88bf0359b89c83 to your computer and use it in GitHub Desktop.
A array except the indexes are fibonacci numbers!
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 FibArray | |
attr_accessor :array, :cache | |
def initialize(array = []) | |
@array = array | |
@cache = [1, 2] # put precomputed results as needed | |
generate_next_fib(array.size - cache.size) | |
end | |
def get(i) | |
check_index_error(i) | |
array[reverse_fib(i)] | |
end | |
def set(i, element) | |
check_index_error(i) | |
array[reverse_fib(i)] = element | |
element | |
end | |
def push(element) | |
generate_next_fib | |
array << element | |
end | |
def pop | |
cache.pop | |
array.pop | |
end | |
def remove(i) | |
check_index_error(i) | |
cache.pop | |
array.delete_at(reverse_fib(i)) | |
end | |
def check_index_error(i) | |
fib_index = reverse_fib(i) | |
raise IndexError if fib_index.nil? | |
end | |
private | |
def fib(fib_i) | |
if fib_i >= cache.size | |
cache[fib_i] = fib(fib_i - 1) + fib(fib_i - 2) | |
end | |
cache[fib_i] | |
end | |
def generate_next_fib(n = 1) | |
n.times { fib(cache.size) } | |
end | |
def reverse_fib(number) | |
cache.index(number) | |
end | |
end |
https://www.reddit.com/r/ruby/comments/9xojgm/recursive_and_nonrecursive_fibonacci/e9uesl0/ if you want to see alternative Fibonacci implementations in ruby that can replace fib
in the source code.
MIT License
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To test it out I ran it on the console using pry