Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@

# A method to reverse the words in a sentence, in place.
# Time complexity: ?
# Space complexity: ?
Comment on lines 3 to 4

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Time & space complexity?

def reverse_sentence(my_sentence)
raise NotImplementedError

def reverse_sentence(test_string)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now you're only reversing the sentence. You then need to do another loop reversing each word. Something to work on.

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?
29 changes: 26 additions & 3 deletions lib/sort_by_length.rb
Original file line number Diff line number Diff line change
@@ -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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically here since you're doing .split you're making a new array of words. So this is O(n)


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