-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_words.rb
More file actions
36 lines (32 loc) · 1.22 KB
/
reverse_words.rb
File metadata and controls
36 lines (32 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def reverse_words(message)
# first we reverse all the characters in the entire message
reverse_characters(message, 0, message.length-1)
# this gives us the right word order
# but with each word backwards
# now we'll make the words forward again
# by reversing each word's characters
# we hold the index of the /start/ of the current word
# as we look for the /end/ of the current word
current_word_start_index = 0
for i in 0..message.length
# found the end of the current word!
if (message[i] == ' ') || (i == message.length)
reverse_characters(message, current_word_start_index, i-1)
# if we haven't exhausted the string our # next word's start is one character ahead
current_word_start_index = i + 1
end
end
return message
end
def reverse_characters(message, front_index, back_index)
# walk towards the middle, from both sides
while front_index < back_index
# swap the front char and back char
message[front_index], message[back_index] = message[back_index], message[front_index]
front_index += 1
back_index -= 1
end
return message
end
message = 'find you will pain only go you recordings security the into if'
puts reverse_words(message)