Created
June 20, 2016 19:06
-
-
Save ctrombley/ceb0242d1e20e0355e8e8a7af171d908 to your computer and use it in GitHub Desktop.
justify.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
describe "JustifySolver" do | |
let (:solver) { JustifySolver.new } | |
it "should justify a sentence" do | |
solver.solve("The quick brown fox jumps over the lazy dog.", 5) | |
.must_equal("The \n" \ | |
"quick\n" \ | |
"brown\n" \ | |
"fox \n" \ | |
"jumps\n" \ | |
"over \n" \ | |
"wthe \n" \ | |
"lazy \n" \ | |
" dog.\n") | |
end | |
end | |
class JustifySolver | |
def solve(sentence, line_length) | |
justified = [] | |
while (sentence.size > 0) | |
chunk = sentence[0..line_length] | |
puts "chunk #{chunk}" | |
spaces_to_add = /\s(\S*)$/.match(chunk)[1].length | |
words = chunk[0...-1 * spaces_to_add].split(" ") | |
puts "words #{words}" | |
puts "spaces_to_add: #{spaces_to_add}" | |
(1...spaces_to_add).each do |i| | |
puts "#{i}" | |
puts "adding space to #{words[spaces_to_add % word.size]}" | |
words[words.size-1 % i] += " " | |
end | |
chunk = words.join("") | |
puts "justified chunk: *#{chunk}*" | |
justified << chunk[0...-2] | |
sentence = sentence[line_length-spaces_to_add..-1] | |
end | |
justified | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment