Skip to content

Instantly share code, notes, and snippets.

@ctrombley
Created June 20, 2016 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrombley/ceb0242d1e20e0355e8e8a7af171d908 to your computer and use it in GitHub Desktop.
Save ctrombley/ceb0242d1e20e0355e8e8a7af171d908 to your computer and use it in GitHub Desktop.
justify.rb
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