From 773f542b38925f175651695aed39a6abcd62b52a Mon Sep 17 00:00:00 2001 From: Linnea Johnson Date: Mon, 18 Nov 2019 23:54:32 -0800 Subject: [PATCH] Finished super digit --- lib/fibonacci.rb | 44 +++++++++++++++++++++++++++++++++++++++- lib/super_digit.rb | 13 ++++++------ test/super_digit_test.rb | 4 ++-- 3 files changed, 52 insertions(+), 9 deletions(-) diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..e95e93c 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -4,5 +4,47 @@ # Space Complexity - ? (should be O(n)) # Hint, you may want a recursive helper method def fibonacci(n) - + return fibonacci_helper(n, solution = [0,1], current = 2) end + +def fibonacci_helper(n, s, current) + + if n < 0 + raise ArgumentError + end + + if n == 0 || n == 1 + return n + end + + if current == n + return s[0] + s[1] + end + + temp = s[1] + s[1] = s[0] + s[1] + s[0] = temp + return fibonacci_helper(n, s, current + 1) +end + +#Iterative + +# def fib(n) +# if n == 0 || n == 1 +# return n +# end +# solution = [0, 1] +# current = 2 +# while current < n +# p current +# p solution, "before" +# temp = solution[1] +# solution[1] = solution[0] + solution[1] +# solution[0] = temp +# # solut + +# current += 1 +# p solution, "after" +# end +# return solution[0] + solution[1] +# end \ No newline at end of file diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..0c8b684 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,15 +1,16 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(n) +# Space Complexity - O(1) def super_digit(n) - + return n if n.to_s.length == 1 + return super_digit(n.digits.sum) end # Time Complexity - ? # Space Complexity - ? -def refined_super_digit(n, k) - -end +# def refined_super_digit(n, k) + +# end \ No newline at end of file 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)