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

reverse sentence MS #38

Open
wants to merge 1 commit 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
50 changes: 49 additions & 1 deletion lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,52 @@
# A method to reverse the words in a sentence, in place.
def reverse_sentence(my_sentence)
raise NotImplementedError
def reverse_sentence(sentence)
return nil if sentence.nil?

finish = nil
start = nil
on_first_word = true

is_finding_whitespace = sentence[-1] == ' '

(sentence.length - 1).downto(0) do |current_index|
current_char = sentence[current_index]

if is_finding_whitespace
if finish.nil? && current_char == ' '
finish = current_index
end

if start.nil? && sentence[current_index - 1] != ' '
start = current_index
end
else
# a word
if finish.nil? && current_char != ' '
finish = current_index
end

if start.nil? && sentence[current_index - 1] == ' '
start = current_index
end
end

if start.nil? && current_index == 0
start = current_index
end

if start && finish
if on_first_word
on_first_word = false
else
word = sentence.slice!(start..finish)
sentence << word
end

start = nil
finish = nil
is_finding_whitespace = !is_finding_whitespace
end
end
end
end