diff --git a/lib/fibonacci.rb b/lib/fibonacci.rb index 7465c25..284b2d0 100644 --- a/lib/fibonacci.rb +++ b/lib/fibonacci.rb @@ -1,8 +1,24 @@ # Improved Fibonacci -# Time Complexity - ? -# Space Complexity - ? (should be O(n)) +# Time Complexity - ? +# Space Complexity - ? O(n) # Hint, you may want a recursive helper method -def fibonacci(n) - + +def fib_helper(solutions, current, n) + raise ArgumentError.new("negative input") if n < 0 + return n if n == 0 || n == 1 + + if current == n + return solutions[0] + solutions[1] + end + + temp = solutions[0] + solutions[0] = solutions[1] + solutions[1] = temp + solutions[1] + + return fib_helper(solutions, current + 1, n) end + +def fibonacci(n) + return fib_helper([0, 1], 2, n) +end \ No newline at end of file diff --git a/lib/super_digit.rb b/lib/super_digit.rb index 33e367f..9e156b1 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,15 +1,29 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(n) +# Space Complexity - O(n) + +def digit_sum(n, sum = 0) + return n if n < 10 + + n.to_s.each_char { |num| sum += num.to_i } + return sum +end + def super_digit(n) - + return n if n < 10 + return super_digit(digit_sum(n)) end -# Time Complexity - ? -# Space Complexity - ? -def refined_super_digit(n, k) - -end - \ No newline at end of file +# Time Complexity - O(n) +# Space Complexity - O(n) +def refined_super_digit(n, k, i = 0) + return n if n < 10 + + sum = digit_sum(n) + sum *= k if i == 0 + i += 1 + + return super_digit(sum) +end \ No newline at end of file diff --git a/test/super_digit_test.rb b/test/super_digit_test.rb index 60da3a1..484e529 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) @@ -15,7 +15,7 @@ # Assert expect(answer).must_equal 5 - end + end it "will return 6 for super_digit(123)" do # Act diff --git a/test/test_helper.rb b/test/test_helper.rb index 9b999a1..c970510 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,7 +1,7 @@ require 'minitest' require 'minitest/autorun' require 'minitest/reporters' -require "minitest/skip_dsl" +# require "minitest/skip_dsl" Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new