I would like to add a few ways to calculate the Fibonacci numbers, for example:
- using the matrix;
- classic recursive;
- with memoization;
and so on
I have a couple of ways to do this, and so I would like some advice.
1. So, the first way is to use the strategy pattern, for example
fibonacci = FibonacciContext.new(FibonacciRecursive.new)
puts fibonacci.compute 10
fibonacci.strategy = FibonacciMatrix.new
puts fibonacci.compute 10
with file structure like:
(math)
├── fibonacci
│ ├── strategies
│ │ ├── fibonacci_recursive.rb
│ │ ├── fibonacci_matrix.rb
│ │ └── fibonacci_golden_ratio.rb
│ ├── strategy.rb
│ └── fibonacci_context.rb
└── fibonacci.rb <--- client file
2. The second way is to make a Fibonacci module with different ways as functions and divide it into several files with this structure:
(math)
├── fibonacci
│ ├── recursive.rb
│ ├── matrix.rb
│ └── golden_ratio.rb
└── fibonacci.rb
where
# fibonacci.rb
require_relative 'fibonacci/recursive.rb'
require_relative 'fibonacci/matrix.rb'
require_relative 'fibonacci/golden_ratio.rb'
module Fibonacci
end
# fibonacci/recursive.rb
module Fibonacci
def recursive(n)
# ...
end
end
...
- The third and simplest is to make just a lot of files in the math folder:
(math)
├── fibonacci_recursive.rb
├── fibonacci_matrix.rb
└── fibonacci_golden_ratio.rb
Well, I have given several ways, but I myself tend to the third, since most of the algorithms are designed in this way. But, on the other hand, it could be a starting point for refactoring the project structure.