Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dionisia Edges reverse_words #30

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
40 changes: 39 additions & 1 deletion lib/reverse_words.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,42 @@
# A method to reverse each word in a sentence, in place.
def reverse_words(my_words)
raise NotImplementedError
# raise NotImplementedError
return my_words if my_words.nil? || my_words.empty?

i = 0 # starting point of sentence
j = my_words.length # ending point of sentence

while i < j
while my_words[i] == " " && i < j
i += 1
end

word_start = i # starting point of next word in sentance

while my_words[i] != " " && i < j
i += 1
end

word_end = i - 1 # end point of word in sentence

word_reverse(my_words, word_start, word_end)
end

Choose a reason for hiding this comment

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

Thought for further improvement: With the last test case scenario " evol ", your algorithm does work because for the first 4 spaces, on line 17 my_words_start will end up being greater than my_words_end. Can you intentionally add consideration for preceding and trailing consecutive white spaces?

return
end

# helper method to reverse a word
def word_reverse(my_words, word_start, word_end)
return nil if my_words == nil || my_words.length == 0

i = word_start # first index of character word word
j = word_end # last index of character in word

while i < j
temp = my_words[i] # swap with temporary variable
my_words[i] = my_words[j]
my_words[j] = temp
i += 1
j -= 1
end
return
end