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
30 changes: 30 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
GEM
remote: http://rubygems.org/
specs:
ansi (1.5.0)
builder (3.2.3)
minitest (5.10.3)
minitest-reporters (1.3.8)
ansi
builder
minitest (>= 5.0)
ruby-progressbar
minitest-skip (0.0.1)
minitest (~> 5.0)
rake (12.3.0)
ruby-progressbar (1.10.1)

PLATFORMS
ruby

DEPENDENCIES
minitest
minitest-reporters
minitest-skip
rake

RUBY VERSION
ruby 2.5.1p57

BUNDLED WITH
1.17.3
41 changes: 37 additions & 4 deletions lib/reverse_sentence.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,39 @@
# A method to reverse the words in a sentence, in place.
# Time complexity: ?
# Space complexity: ?
def reverse_sentence(my_sentence)
raise NotImplementedError
# Time complexity: O(n*m)???
# Space complexity: O(1)
def reverse_helper(string, s, e)
pairs = (e + 1 - s)/2
pairs.times do
temp = string[s]
string[s] = string[e]
string[e] = temp
s += 1
e -= 1
end
end

def reverse_sentence(sentence)
return sentence if sentence == nil || sentence == "" || sentence.include?("\s") == false
reverse_helper(sentence, 0, (sentence.length - 1))

j = 0
spaces = []
while j <= sentence.length
if sentence[j] == " "
spaces << j
if spaces.length == 1
# reverse the first word
reverse_helper(sentence, 0, (j - 1))
elsif spaces.length > 1
# reverse the middle word
reverse_helper(sentence, (spaces[-2] + 1), (j - 1))
end
elsif sentence[j] == nil
# reverse the last word
reverse_helper(sentence, (spaces[-1] + 1), (j - 1))
end
j += 1
end

return sentence
end
28 changes: 22 additions & 6 deletions lib/sort_by_length.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
# A method which will return an array of the words in the string
# sorted by the length of the word.
# Time complexity: ?
# Space complexity: ?
def sort_by_length(my_sentence)
raise NotImplementedError, "Method not implemented"
end
# sorted by the length of the word.
# Time complexity: O(n2)
# Space complexity: O(n)

def sort_by_length(sentence)
#Step_1: break the sentence into an array of words
array = sentence.split(/\W+/)
#Step_2: use insertion sort to sort the array
i = 1
while i < array.length
to_insert = array[i]
j = i
while j > 0 && array[j-1].length > to_insert.length
array[j] = array[j-1]
j -= 1
end
array[j] = to_insert
i += 1
end

return array
end
File renamed without changes.