From 7ee59ca6ff31e091f248621f475d62a217f7b628 Mon Sep 17 00:00:00 2001 From: Vi Date: Mon, 23 Sep 2019 17:51:02 -0700 Subject: [PATCH] finished both methods, passed tests --- lib/reverse_sentence.rb | 27 ++++++++++++++++++++++++--- lib/sort_by_length.rb | 25 +++++++++++++++++++------ 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..01e09af 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,27 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) +# Space complexity: O(n) +# Not pleased with how regex captures the whitespaces and think that it creates unneccesary iteration for the program to run. I couldn't figure a better one out though. + def reverse_sentence(my_sentence) - raise NotImplementedError + if my_sentence == nil + return nil + end + + my_sentence_array = my_sentence.split(/(\S+|\s{1,})/) + length = my_sentence_array.length + index = 0 + temp = 0 + + while index < length / 2 + temp = my_sentence_array[index] + my_sentence_array[index] = my_sentence_array[length - index - 1] + my_sentence_array[length - index - 1] = temp + index += 1 + end + + reversed_sentence = my_sentence_array.join('') + my_sentence[0..my_sentence.length] = reversed_sentence + end + diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..2c13c2e 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,20 @@ -# 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(n) def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" -end + my_sentence_array = my_sentence.split(' ') + length = my_sentence_array.length + i = 1 + + while i < length + to_insert = my_sentence_array[i] + j = i + + while j > 0 && my_sentence_array[j-1].length > to_insert.length + my_sentence_array[j] = my_sentence_array[j - 1] + j -= 1 + end + my_sentence_array[j] = to_insert + i += 1 + end + return my_sentence_array +end \ No newline at end of file