Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions lib/fibonacci.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,30 @@
# Improved Fibonacci

# Time Complexity - ?
# Space Complexity - ? (should be O(n))
# Time Complexity - ? O(n)
# Space Complexity - ? O(n)
# Hint, you may want a recursive helper method
def fibonacci(n)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works, but you're keeping the entire list of fibonacci numbers for the whole length of the recursion.  Instead you should only keep the last 2 fibonacci numbers.


return fib_helper({}, n)

end


def fib_helper(solutions, n)
if solutions.include?(n)
return solutions[n]
end

if n == 0
solutions[n] = 0
return 0
elsif n == 1
solutions[n] = 1
return 1
elsif n >= 2
solutions[n] = (fib_helper(solutions, n-2) + fib_helper(solutions, n-1))
return solutions[n]
else
raise ArgumentError
end

end
27 changes: 24 additions & 3 deletions lib/super_digit.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
# Superdigit

# Time Complexity - ?
# Space Complexity - ?
# Time Complexity - O(n)
# Space Complexity - O(n)
def super_digit(n)
super_digit_helper({}, n)

end


def super_digit_helper(solutions, n)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting approach. Nice work. This would work more often if you had repeated uses of super_digit

if solutions[n]
return solutions[n]
end

if n.to_s.length == 1
solutions[n] = n
return solutions[n]
end

string_num = n.to_s

sum = 0
string_num.length.times do |i|
sum += (string_num[i].to_i)
end

solutions[n] = super_digit_helper(solutions, sum)
return solutions[n]
end

# Time Complexity - ?
# Space Complexity - ?
Expand Down
4 changes: 2 additions & 2 deletions test/super_digit_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require_relative "test_helper"

xdescribe "super_digit" do
describe "super_digit" do
it "will return 2 for super_digit(9875)" do
# Act
answer = super_digit(9875)
Expand Down Expand Up @@ -33,7 +33,7 @@
expect(answer).must_equal 6
end

describe "refined superdigit" do
xdescribe "refined superdigit" do
it "will return 1 for n = 1 and k = 1" do
# Act
answer = refined_super_digit(1, 1)
Expand Down