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
43 changes: 39 additions & 4 deletions lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
# A method to reverse the words in a sentence, in place.
# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n^2), n == length of my_sentence string
# Space complexity: O(1)
def reverse_sentence(my_sentence)
raise NotImplementedError
end
if my_sentence == "" || my_sentence == nil
return my_sentence
end
a = 0
max_index = my_sentence.length - 1
b = max_index
while a < b do
temp = my_sentence[a]
my_sentence[a] = my_sentence[b]
my_sentence[b] = temp
a += 1
b -=1
Comment on lines +11 to +16

Choose a reason for hiding this comment

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

Notice that you're reversing twice in this method. Could you DRY this up by creating a helper method to reverse a substring?

end
i = 0
while i < max_index do
if my_sentence[i] == " "
i += 1
else
j = i + 1
while j <= max_index && my_sentence[j] != " " do
j += 1
end
word_end_index = j
j -= 1
while i < j do
temp_i = my_sentence[i]
my_sentence[i] = my_sentence[j]
my_sentence[j] = temp_i
i += 1
j -= 1
end
i = word_end_index
end
end
return my_sentence
end

25 changes: 22 additions & 3 deletions lib/sort_by_length.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
# 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), n == number of words in the sentence
# Space complexity: 1

Choose a reason for hiding this comment

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

Technically space complexity is O(n) because you are doing a .split.

def sort_by_length(my_sentence)

Choose a reason for hiding this comment

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

Nicely done selection sort.

raise NotImplementedError, "Method not implemented"
sentence_array = my_sentence.split
length = sentence_array.length
(0...(length - 1)).each do |i|
min_index = i
j = i + 1
while j < length
if sentence_array[j].length < sentence_array[min_index].length
min_index = j
end
j += 1
end
if min_index != i
temp = sentence_array[min_index]
sentence_array[min_index] = sentence_array[i]
sentence_array[i] = temp
end
i += 1
end
return sentence_array
end

File renamed without changes.