diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..72f5fc8 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,19 @@ + # A method to reverse the words in a sentence, in place. # Time complexity: ? # Space complexity: ? -def reverse_sentence(my_sentence) - raise NotImplementedError + +def reverse_sentence(test_string) + half = test_string.length / 2 + # loop through elements n/2 times (ignores central element if length is odd) + half.times do |i| + # swap all characters/whitespace (" Yoda" => "adoY ") + test_string[i], test_string[-i-1] = test_string[-i-1], test_string[i] + end + + # can't figure out how to reverse letters in each word :( + + return test_string end + +# per Dianna, I can reverse words in a new array and then reassign values to original array. Does this count as modifying in place? \ No newline at end of file diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..d3c617b 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,30 @@ # 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: This is an insertion sort with two loops, so time complexity is O(n^2) / quadratic +# Space complexity: O(1) / constant + def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" + # split sentence into array of strings + my_sentence_words = my_sentence.split(" ") + array_length = my_sentence_words.length + i = 1 + # set condition for outer loop to run + while i < array_length + # declare value for word to be considered + to_insert = my_sentence_words[i] + j = i # j = 4 + # set conditions for inner loop to run + while j > 0 && my_sentence_words[j-1].length > to_insert.length + # if conditions evaluate true, move word at [j] down one position + my_sentence_words[j] = my_sentence_words[j-1] + # decrement counter for inner loop + j -= 1 + end + # not 100 percent sure what this variable is doing but I know it's necessary + my_sentence_words[j] = to_insert + # increment counter for outer loop + i += 1 + end + return my_sentence_words end +