From 83d2869ed16a607fdd51ced30b0241767c1160bd Mon Sep 17 00:00:00 2001 From: Linnea Johnson Date: Wed, 13 Nov 2019 23:51:54 -0800 Subject: [PATCH] Palindrome, factorial, and reverse complete --- lib/recursive-methods.rb | 36 +++++++++++++++++++++++++--------- test/recursion_writing_test.rb | 4 ++-- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/lib/recursive-methods.rb b/lib/recursive-methods.rb index fbf6faa..4be37df 100644 --- a/lib/recursive-methods.rb +++ b/lib/recursive-methods.rb @@ -1,15 +1,25 @@ # 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" + if n < 0 + raise ArgumentError + elsif n == 0 || n == 1 + return 1 + else + return n * (factorial(n - 1)) + end end -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) +# Space complexity: O(n) def reverse(s) - raise NotImplementedError, "Method not implemented" + if s.length <= 1 + return s + else + return reverse(s[1..-1]) + s[0] + end end # Time complexity: ? @@ -36,10 +46,18 @@ def search(array, value) raise NotImplementedError, "Method not implemented" end -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) +# Space complexity: O(n) def is_palindrome(s) - raise NotImplementedError, "Method not implemented" + if s.length == 1 || s.length == 0 + return true + end + + if s[0] != s[-1] + return false + end + + return is_palindrome(s[1...-1]) end # Time complexity: ? diff --git a/test/recursion_writing_test.rb b/test/recursion_writing_test.rb index 820810e..0e2c56b 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" @@ -260,7 +260,7 @@ end end -xdescribe "is_palindrome" do +describe "is_palindrome" do it "will return true for emptystring" do # Arrange string = ""