Skip to content

Instantly share code, notes, and snippets.

@harsh183
Last active April 16, 2021 15:33
Show Gist options
  • Save harsh183/2c3a83ec356a16d4cf88bf0359b89c83 to your computer and use it in GitHub Desktop.
Save harsh183/2c3a83ec356a16d4cf88bf0359b89c83 to your computer and use it in GitHub Desktop.
A array except the indexes are fibonacci numbers!
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
@harsh183
Copy link
Author

harsh183 commented Jul 8, 2019

To test it out I ran it on the console using pry

> farray = FibArray.new [:a, :b, :c, :d, :e]
=> #<FibArray:0x000055f0330ebea0 @array=[:a, :b, :c, :d, :e], @cache=[1, 2, 3, 5, 8]>
> farray.get(5)
=> :d
> farray.set(3, :z)
=> :z
> farray.get(3)
=> :z
> farray.array
=> [:a, :b, :z, :d, :e]
> farray.push :f
=> 1
> farray.get(8)
=> :e
> farray.cache # Cached fibonacci results
=> [1, 2, 3, 5, 8, 13]
> farray.pop
=> :e
> farray.remove(1)
=> :a
> farray.get(7) # A fibonacci number that doesn't exist
IndexError: IndexError
from fibArray.rb:29:in `check_index_error'

@harsh183
Copy link
Author

harsh183 commented Jul 8, 2019

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.

@harsh183
Copy link
Author

harsh183 commented May 24, 2020

MIT License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment