diff --git a/lib/recursive-methods.rb b/lib/recursive-methods.rb index fbf6faa..19f176b 100644 --- a/lib/recursive-methods.rb +++ b/lib/recursive-methods.rb @@ -1,27 +1,50 @@ # Authoring recursive algorithms. Add comments including time and space complexity for each method. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n), where n is the value of the number +# Space complexity: O(n), where n is the value of the number def factorial(n) - raise NotImplementedError, "Method not implemented" + if n == 0 + return 1 + elsif n.nil? || n < 0 + raise ArgumentError, "This value is not valid." + end + + return n * factorial(n-1) + end -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n), where n is the length of the string +# Space complexity: O(n), because there will be n layers to the call stack. def reverse(s) - raise NotImplementedError, "Method not implemented" + + if s.length == 0 + return s + else + return s[s.length-1] + reverse(s[0, s.length-1]) + end + end -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n), where n is the length of the string +# Space complexity: O(n), because there will be n layers to the call stack. def reverse_inplace(s) - raise NotImplementedError, "Method not implemented" + + if s.length == 0 + return s + else + return s[s.length-1] + reverse(s[0, s.length-1]) + end + end # Time complexity: ? # Space complexity: ? def bunny(n) - raise NotImplementedError, "Method not implemented" + if n % 2 == 0 + return 0 + else + return n + bunny(2-1) + end end # Time complexity: ? @@ -46,4 +69,4 @@ def is_palindrome(s) # Space complexity: ? def digit_match(n, m) raise NotImplementedError, "Method not implemented" -end \ No newline at end of file +end diff --git a/specs/recursion_writing_spec.rb b/specs/recursion_writing_spec.rb index d8fb1ed..1fcb5eb 100644 --- a/specs/recursion_writing_spec.rb +++ b/specs/recursion_writing_spec.rb @@ -38,7 +38,7 @@ end end -xdescribe "reverse" do +describe "reverse" do it "will reverse 'cat'" do # Arrange string = "cat" @@ -84,7 +84,7 @@ end -xdescribe "reverse_in_place" do +describe "reverse_in_place" do it "will reverse 'cat'" do # Arrange string = "cat" @@ -129,7 +129,7 @@ end end -xdescribe "bunny" do +describe "bunny" do it "returns 0 for 0 bunnies" do # Arrange count = 0 @@ -331,4 +331,4 @@ # Assert expect(answer).must_equal 3 end -end \ No newline at end of file +end