diff --git a/Gemfile b/Gemfile index 46677aa..16ca0b3 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,6 @@ source 'http://rubygems.org' -ruby '2.5.1' +ruby '2.5.5' gem 'rake' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..c1e2af5 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,30 @@ +GEM + remote: http://rubygems.org/ + specs: + ansi (1.5.0) + builder (3.2.3) + minitest (5.12.0) + minitest-reporters (1.3.8) + ansi + builder + minitest (>= 5.0) + ruby-progressbar + minitest-skip (0.0.1) + minitest (~> 5.0) + rake (12.3.3) + ruby-progressbar (1.10.1) + +PLATFORMS + ruby + +DEPENDENCIES + minitest + minitest-reporters + minitest-skip + rake + +RUBY VERSION + ruby 2.5.5p157 + +BUNDLED WITH + 2.0.2 diff --git a/lib/reverse_sentence.rb b/lib/reverse_sentence.rb index 3fe7cac..7c92119 100644 --- a/lib/reverse_sentence.rb +++ b/lib/reverse_sentence.rb @@ -1,6 +1,37 @@ +def reverse_sentence_from_start_to_end(my_sentence, start_index, end_index) + half_width = (end_index - start_index) / 2 + count = (half_width + 1).to_i + count.times do |i| + temp = my_sentence[start_index + i] + my_sentence[start_index + i] = my_sentence[end_index - i] + my_sentence[end_index - i] = temp + end +end + # A method to reverse the words in a sentence, in place. -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n**2) +# Space complexity: O(1) def reverse_sentence(my_sentence) - raise NotImplementedError + if my_sentence.nil? + return + end + + reverse_sentence_from_start_to_end(my_sentence, 0, my_sentence.length - 1) + + start_index = nil + my_sentence.each_char.with_index do |letter, index| + if letter != " " && start_index.nil? + start_index = index + elsif letter == " " && !start_index.nil? + end_index = index - 1 + reverse_sentence_from_start_to_end(my_sentence, start_index, end_index) + start_index = nil + end + end + + if !start_index.nil? + reverse_sentence_from_start_to_end(my_sentence, start_index, my_sentence.length - 1) + end end + +reverse_sentence("Yoda is awesome") diff --git a/lib/sort_by_length.rb b/lib/sort_by_length.rb index a5713ad..8c132e2 100644 --- a/lib/sort_by_length.rb +++ b/lib/sort_by_length.rb @@ -1,7 +1,24 @@ # 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) +# Space complexity: O(n) def sort_by_length(my_sentence) - raise NotImplementedError, "Method not implemented" -end + words = my_sentence.split(" ") + results = [] + words.each do |word| + if results.length > 0 + results.each_with_index do |result, index| + if word.length < result.length + results.insert(index, word) + break + elsif index == (results.length - 1) + results << word + break + end + end + else + results << word + end + end + return results +end diff --git a/test/sort_by_length.rb b/test/sort_by_length_test.rb similarity index 100% rename from test/sort_by_length.rb rename to test/sort_by_length_test.rb