Created
July 3, 2019 18:03
-
-
Save jubishop/aba83c8d1cd5ad4b69b7cf1ce2663e39 to your computer and use it in GitHub Desktop.
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
def spacers(num, divisor) | |
ans = Array.new | |
until (num == 0) | |
space = num / divisor | |
ans.push(space) | |
num -= space | |
divisor -= 1 | |
end | |
return ans.reverse | |
end | |
def full_justify(words, max_width) | |
lengths = words.map { |word| word.length } | |
cur_word, line, output = 0, Array.new, Array.new | |
loop { | |
line.push(lengths[cur_word]) | |
if (cur_word == words.length-1 or line.sum {|length| length+1} + lengths[cur_word+1] > max_width) | |
if (line.length == 1) | |
output.push(words[cur_word] + (" " * (max_width - lengths[cur_word]))) | |
elsif (cur_word == words.length-1) | |
line_str = "" | |
until (line.length == 1) | |
line_str += words[cur_word - line.length + 1] + " " | |
line.shift | |
end | |
line_str += words[cur_word] | |
line_str += " " * (max_width - line_str.length) | |
output.push(line_str) | |
else | |
spaces = spacers(max_width - line.sum{|length| length}, line.length-1) | |
line_str = "" | |
until (line.length == 1) | |
line_str += words[cur_word - line.length + 1] + (" " * spaces.shift) | |
line.shift | |
end | |
line_str += words[cur_word] | |
output.push(line_str) | |
end | |
line.clear | |
end | |
break if cur_word == words.length-1 | |
cur_word += 1 | |
} | |
return output | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment