diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..b8a24e0 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,50 @@ # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? -def reverse_sentence(my_sentence) - raise NotImplementedError +# Time complexity: O(n + m) - +# Reverse_Sentence +# - 1st while loop: O(.5n) where n is the number of letters +# - 2nd while loop: O(n) where n is the number of letters +# Reverse +# - O(m): where m is the number of words +# Space complexity: O(1) + +def reverse(text, text_start, text_end) + i = 0 + ((text_end - text_start)/2).times do + temp_char = text[text_start + i] + text[text_start + i] = text[text_end - i - 1] + text[text_end - i - 1] = temp_char + i += 1 + end end + + +def reverse_sentence(my_sentence) + return nil if my_sentence.nil? + letter = 0 + length = my_sentence.length + + end_char = length - 1 + while letter < my_sentence.length/2 do + temp_char = my_sentence[letter] + my_sentence[letter] = my_sentence[length - 1 - letter] + my_sentence[length - 1 - letter] = temp_char + letter += 1 + end + + letter = 0 + while letter < my_sentence.length do + while my_sentence[letter] == " " + letter += 1 + end + start_index = letter + + while my_sentence[letter] != " " && letter < my_sentence.length + letter += 1 + end + end_index = letter + + reverse(my_sentence, start_index, end_index) + end + + return my_sentence +end \ No newline at end of file diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..fa42b16 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,22 @@ # 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 + return nil if my_sentence.nil? + + my_sorted_array = [] + my_array = my_sentence.split + + until my_array.length == 0 do + current_word = my_array[0] + my_array.each do |word| + if word.length < current_word.length + current_word = word + end + end + my_sorted_array.push(current_word) + my_array.delete(current_word) + end + return my_sorted_array +end \ No newline at end of file diff --git a/test/sort_by_length.rb b/test/sort_by_length_test.rb similarity index 100% rename from test/sort_by_length.rb rename to test/sort_by_length_test.rb