diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..ca5b684 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,23 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) because the amount of time it will take will increase as the length of the input increases. +# Space complexity: O(n) because the space increases as the inout increases. def reverse_sentence(my_sentence) - raise NotImplementedError + words = my_sentence.split(" ") + length = words.length + + mid = (length)/2 + i = 0 + k = 1 + while i < mid do + j = words[length-k] + words[length-k] = words[i] + words[i] = j + i += 1 + k += 1 + end + + if i == mid + my_sentence = words.join(", ") + return my_sentence + end end diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..1ed82fc 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,31 @@ # A method which will return an array of the words in the string # sorted by the length of the word. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n**2) quadratice because there is a while loop with an if statemeny inside of it. +# Space complexity: O(n) linear because the array will increase the same size of the increas in size of the string. def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" + if my_sentence.nil? || my_sentence == "" + return [] + end + word_array = my_sentence.split(" ") + sorted = [] + sorted << word_array[0] + + + word_array.each do |word| + index = 0 + while index < word_array.length + if word.length < sorted[index].length + sorted.insert(index, word) + break + elsif word.length == sorted[index].length + sorted.insert(index+1,word) + break + elsif index == sorted.length-1 + sorted.insert(index+1,word) + break + end + index += 1 + end + end + return sorted.uniq end diff --git a/test/sort_by_length.rb b/test/sort_by_length.rb index c38d976..57c55c3 100644 --- a/test/sort_by_length.rb +++ b/test/sort_by_length.rb @@ -1,3 +1,4 @@ +require "pry" require_relative "test_helper" describe "sort_by_length" do @@ -8,11 +9,11 @@ it "will return an array of words, by length" do expect(sort_by_length("I love Ada")).must_equal ["I", "Ada", "love"] end - + it "will return an array of words by length, words that are of equal length will appear in the order they appear" do expect(sort_by_length("words of equal length")).must_equal ["of", "words", "equal", "length"] end - + it "will return an array of words by length, words that are of equal length will appear in the order they appear" do expect(sort_by_length("I love great awesome words")).must_equal ["I", "love", "great", "words", "awesome"] end