From dd57fffb397c090571e0a2eb87e36b6f3ea90501 Mon Sep 17 00:00:00 2001 From: Mariya Burrows Date: Mon, 18 Nov 2019 20:48:54 -0800 Subject: [PATCH 1/2] completed dynamic programming hw --- lib/fibonacci.rb | 28 +++++++++++++++++++++++++--- lib/super_digit.rb | 23 ++++++++++++++++++++++- test/super_digit_test.rb | 4 ++-- 3 files changed, 49 insertions(+), 6 deletions(-) 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..e9b6909 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -3,9 +3,30 @@ # Time Complexity - ? # Space Complexity - ? 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) From 7d823e567fa53b7f245e98c44d9ae8bfe48ed43d Mon Sep 17 00:00:00 2001 From: Mariya Burrows Date: Tue, 19 Nov 2019 14:02:13 -0800 Subject: [PATCH 2/2] added order n guesses --- lib/super_digit.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/super_digit.rb b/lib/super_digit.rb index e9b6909..4214a00 100644 --- a/lib/super_digit.rb +++ b/lib/super_digit.rb @@ -1,7 +1,7 @@ # Superdigit -# Time Complexity - ? -# Space Complexity - ? +# Time Complexity - O(n) +# Space Complexity - O(n) def super_digit(n) super_digit_helper({}, n)