diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..9ec2806 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,30 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n^2) +# Space complexity: O(1) def reverse_sentence(my_sentence) - raise NotImplementedError + return nil if my_sentence == nil + + len = my_sentence.length + + (len / 2).times do |i| + temp = my_sentence[len - i - 1] + my_sentence[len - i - 1] = my_sentence[i] + my_sentence[i] = temp + end + + first_index = 0 + + len.times do |j| + if my_sentence[j + 1] == " " || j == len - 1 + ((j - first_index + 1) / 2).times do |k| + temp = my_sentence[j - k] + my_sentence[j - k] = my_sentence[first_index + k] + my_sentence[first_index + k] = temp + end + + first_index = j + 2 + end + end + + return my_sentence end diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..44c8785 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) +# Space complexity: O(1) def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" + + # I'm assuming split is O(n), + # can't imagine it needing more than one pass through n + sent_array = my_sentence.split(" ") + count = sent_array.length + + if count == 0 + return sent_array + end + + i = 1 + while i < count + to_insert = sent_array[i] + j = i + + while j > 0 && sent_array[j-1].length > to_insert.length + sent_array[j] = sent_array[j-1] + j -= 1 + end + + sent_array[j] = to_insert + i += 1 + end + + return sent_array end diff --git a/test/sort_by_length.rb b/test/sort_by_length_test.rb similarity index 98% rename from test/sort_by_length.rb rename to test/sort_by_length_test.rb index c38d976..626ecbe 100644 --- a/test/sort_by_length.rb +++ b/test/sort_by_length_test.rb @@ -8,12 +8,12 @@ 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 -end \ No newline at end of file +end