Skip to content

Commit 0899168

Browse files
authored
Create fibonacci_memoization.rb
1 parent 513070d commit 0899168

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/ruby/fibonacci_memoization.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def fibonacci(n, memo = {})
2+
if n <= 1
3+
return 1
4+
end
5+
6+
# Check if the result is already memoized
7+
if memo.key?(n)
8+
return memo[n]
9+
end
10+
11+
# Calculate Fibonacci recursively and store the result in memoization
12+
result = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
13+
memo[n] = result
14+
15+
return result
16+
end
17+
18+
n = 16
19+
puts "Fib(#{n}): #{fibonacci(n)}"

0 commit comments

Comments
 (0)