diff --git a/lib/recursive-methods.rb b/lib/recursive-methods.rb index fbf6faa..4469db9 100644 --- a/lib/recursive-methods.rb +++ b/lib/recursive-methods.rb @@ -1,41 +1,76 @@ # Authoring recursive algorithms. Add comments including time and space complexity for each method. -# Time complexity: ? -# Space complexity: ? +# Time complexity: o(n) +# Space complexity: o(n) def factorial(n) - raise NotImplementedError, "Method not implemented" + # raise NotImplementedError, "Method not implemented" + if n < 0 + raise ArgumentError + elsif n <= 1 + return 1 + else + n * factorial(n-1) + end end -# Time complexity: ? -# Space complexity: ? +# Time complexity: o(n^2) +# Space complexity: o(n^2) def reverse(s) - raise NotImplementedError, "Method not implemented" + # raise NotImplementedError, "Method not implemented" + if s.length <= 1 + return s + else + return s[-1] + reverse(s[0..-2]) + end end -# Time complexity: ? -# Space complexity: ? +# Time complexity: +# Space complexity: def reverse_inplace(s) raise NotImplementedError, "Method not implemented" + end -# Time complexity: ? -# Space complexity: ? + +# Time complexity: o(n) +# Space complexity: o(n) def bunny(n) - raise NotImplementedError, "Method not implemented" + # raise NotImplementedError, "Method not implemented" + if n == 0 + return 0 + else + return 2 + bunny(n-1) + end end -# Time complexity: ? -# Space complexity: ? + +# Time complexity: o(n) +# Space complexity: o(n^2) def nested(s) - raise NotImplementedError, "Method not implemented" + # raise NotImplementedError, "Method not implemented" + if s == "" + return true + elsif s[0] == "(" && s[-1] == ")" && nested(s[1...-1]) + return true + else + return false + end end # Time complexity: ? # Space complexity: ? def search(array, value) - raise NotImplementedError, "Method not implemented" + # raise NotImplementedError, "Method not implemented" + if array.length == 0 + return false + elsif value == array[0] + return true + else + return search(array[1..-1], value) + end end + # Time complexity: ? # Space complexity: ? def is_palindrome(s) diff --git a/test/recursion_writing_test.rb b/test/recursion_writing_test.rb index 820810e..cdfa689 100644 --- a/test/recursion_writing_test.rb +++ b/test/recursion_writing_test.rb @@ -38,7 +38,7 @@ end end -xdescribe "reverse" do +describe "reverse" 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 @@ -164,7 +164,7 @@ end end -xdescribe "nested" do +describe "nested" do it "will return true for empystring" do # Arrange string = "" @@ -210,7 +210,7 @@ end end -xdescribe "search" do +describe "search" do it "will return false for empty array" do # Arrange item = "a"