diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..14e7de3 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -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) - + 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 \ No newline at end of file diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..4214a00 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -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) + 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 - ? diff --git a/test/super_digit_test.rb b/test/super_digit_test.rb index 60da3a1..20973f1 100644 --- a/test/super_digit_test.rb +++ b/test/super_digit_test.rb @@ -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) @@ -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)